spring

[ Spring ] 스프링 MyBatis 라이브러리 추가, SQLSessionFactory 설정

괴발새발개발자 2022. 7. 8. 17:46

1. MyBaits 라이브러리 추가

MyBatis를 사용하기 위해선 mybatis / mybatis-spring / spring-jdbc / spring-tx 총 4개의 라이브러리가 필요하다. MyBatis-Spring은 스프링과 MyBatis 를 연동 시켜주는 라이브러리입니다.

 spring-jdbc와 spring-tx는 스프링에서 데이터베이스 처리와 트랜잭션 처리를 하는 라이브러리입니다. MyBatis와 무관해 보이지만 추가하지 않은 경우에는 에러가 발생하기 때문에 추가해준다.

 

1) pom.xml 에 추가

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

 

2. SQLSessionFactory 설정

 - MyBatis에서 가장 핵심적인 객체는 SQLSession 임. SQLSession객체는 Connection을 생성하거나 원하는 SQL을 전달하고, 결과를 리턴 하도록 해줌.

- 이러한 SQLSession을 만들어 내는 객체가 SQLSessionFactory임. 이 객체(SQLSessionFactory)는 MyBatis-spring 라이브러리의 클래스임.

 - 스프링에서 SQLSEssionFactory 객체를 인식 시키기 위해서 SqlSessionFactoryBean을 사용함. 

 1)  root-context.xml에 추가

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>	
	</bean>

 

3. 테스트

: SqlSessionFactoryBean을 이용해서 SqlSession을 사용해보는 테스트

 

 1) 기존 DataSourceTests.java 클래스에 테스트할 코드를 추가

- SqlSessionFacory 객체를 주입

- try문에 SqlSession 객체를 인스턴스화 하는 코드와 출력문 코드를 추

package org.pky.persistence;

import java.sql.Connection;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.extern.log4j.Log4j;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Log4j
public class DataSourceTests {
	
	@Autowired
	private DataSource ds;
	
	@Autowired
	private SqlSessionFactory sessionFactory;
	
	@Test
	public void testConnection2() {
		try(SqlSession session = sessionFactory.openSession();
			Connection con = session.getConnection()){
			
			log.info(session);
			log.info(con);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 2) JUnit 테스트

 

 3) 결과 확인

 

INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1d8bd0de, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@45ca843, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@11c9af63, org.springframework.test.context.support.DirtiesContextTestExecutionListener@757acd7b, org.springframework.test.context.transaction.TransactionalTestExecutionListener@36b4fe2a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@574b560f, org.springframework.test.context.event.EventPublishingTestExecutionListener@ba54932]
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
WARN : com.zaxxer.hikari.util.DriverDataSource - Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO : org.pky.persistence.DataSourceTests - org.apache.ibatis.session.defaults.DefaultSqlSession@7180e701
INFO : org.pky.persistence.DataSourceTests - HikariProxyConnection@1311544814 wrapping oracle.jdbc.driver.T4CConnection@303e3593
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

 

 

< 출처 >

https://kimvampa.tistory.com/58?category=800652 

 

[Spring][05-1]MyBatis 라이브러리 추가, SQLSessionFactory 설정

개인 공부 후 자료를 남기기 위한 목적이기에 내용 상에 오류가 있을 수 있습니다. git주소(Oracle DB) : https://github.com/sjinjin7/blog_study git주소(MySQL DB) : https://github.com/sjinjin7/..

kimvampa.tistory.com