main
[Spring legacy] Mybatis 연결하기 본문
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
'Java > Spring' 카테고리의 다른 글
[Spring] commons-fileupload 기본 설정 및 테스트 (0) | 2023.04.23 |
---|---|
[Spring legacy] Oracle DB 연결하기 (ojdbc11/jdk11) (0) | 2023.04.22 |
[Spring legacy] 프로젝트 초기 설정 (STS3/Java11/tomcat 9.0) (0) | 2023.04.22 |
[STS] spring legacy project 없는 경우 (0) | 2023.04.22 |
[Spring] Tomcat 10.1 다운로드 및 설정 (Java 11/Windows/Eclipse/STS) (0) | 2023.04.22 |
Comments