Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

main

[Spring legacy] Mybatis 연결하기 본문

Java/Spring

[Spring legacy] Mybatis 연결하기

1984 2023. 4. 22. 23:02

1. pom.xml 에 Mybatis 관련 라이브러리 추가 (Maven Repository 참조)

* mybatis

* mybatis-spring

* spring-tx (데이터 베이스 처리와 트랜잭션 처리)

* spring-jdbc

<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

2. root-context.xml > namespace 추가

추가된 namespaces

4. DataSource Bean 등록 (Username, password 확인)

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
    <property name="username" value="root"></property>
    <property name="password" value="root_password"></property>
</bean>

5. SqlSessionFactory Bean 등록

SqlSessionFactory : SQL Sesstion을 통해서 Connection을 작성하거나 원하는 SQL을 전달하고, 그 결과를 리턴 받는 구조로 작성한다. SqlSessionFactory를 등록하는 작업은 SqlSessionFactoryBean을 이용한다.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>    
    <property name="configLocation" value="classpath:/mybatis-config.xml"></property>        
</bean>

6. mybatis-config.xml 생성 (위치 : src/main/resources)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
<configuration>

</configuration>

 

7. MyBatis 연결 테스트 코드 작성 및 실행

package com.example.persistence;

import java.sql.Connection;

import javax.inject.Inject;
import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class DataSourceTests {

	@Inject
	private DataSource ds;

	@Test
	public void testConnection() {
		try (Connection conn = ds.getConnection()) {
			System.out.println("conn 객체 >> " + conn);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

8. 끝

728x90
Comments