-
스프링 MyBatis 연동스프링 프레임워크 2019. 4. 29. 02:54
Data Access Layer를 구성하는 DAO(Data Access Object)에서 Mybatis를 호출하고 사용하는 구조로 만들어진다.
MyBatis의 장점
spring-jdbc 모듈은 스프링이 그 자체로 가지고 있는 JDBC용 개발 모듈로 이 자체만 이용해서 개발할 수 있지만, MyBatis만큼 개발의 편리함을 제공하지는 못한다.
간결한 코드의 처리
- try ~ catch ~ finally를 이용하는 처리 등 데이터를 처리하기까지 많은 코드를 작성해야하는데
MyBatis는 이러한 코드를 줄여 줄 수 있다.
SQL의 분리운영
- 별도의 파일을 작성하는 번거로운 작업 없이 XML 혹은 어노테이션 방식으로 SQL문을 별도로 처리하는 작업이 가능하다.
Spring의 연동으로 자동화된 처리
- 스프링프레임워크와 MyBatis를 연계하는 Mybatis-Spring 라이브러리를 이용하면, 개발자는 직접 SQL문의 호출 없이 원하는 결과를 얻을 수 있다.
동적 SQL을 이용한 제어 기능
- MyBatis는 기본적으로 SQL문을 처리하기는 하지만, 약간의 제어문이나 루프등의 처리 기능을 가지고 있기에
SQL과 관련된 처리를 Java코드에서 분리할 수 있다.
Spring과 MyBatis 사이에는 두 프레임워크의 접착제 역활을 하는 MyBatis-Spring 모듈이 필요하게 된다.
이를 위해서 porm.xml에 다음과 같은 프레임워크, 라이브러리를 추가해야한다.
추가한 라이브러리가 정상적으로 다운로드 되었다면 root-context.xml에서는 조금 다양한 태그를 사용할 수 있다.
<!-- 마이바티스 라이브러리 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- 스프링과 마이바티스를 연결하는 라이브러리 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- 스프링에서 JDBC를 사용하기 위한 라이브러리 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework-version}</version> </dependency>
root-context.xml 파일의 수정
스프링 프레임워크에 다양한 설정을 하기 위해서는 STS상에서 Namaspace 탭을 이용해 사용 가능한 XML 태그의 폭을 넓혀 줘야 한다. aop, context, jdbc, mybatis-spring를 추가한다.
JDBC의 커넥션을 처리하는 기능을 가지고 있는 DataSource 설정하기
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property> <property name="url" value="jdbc:log4jdbc:oracle:thin:@127.0.0.1:1521:xe"></property> <property name="username" value="board_ex"></property> <property name="password" value="1234"></property> </bean>
설정에 보이는 class 속성의 값을 보면 'org.springframework.jdbc.xxx'로 시작하는 것을 볼 수 있다.
이 속성의 값에 해당하는 클래스가 존재해야 하기 때문에 이전 단계에서 spring-jdbc 모듈을 추가한것이다.
id라는 속성은 스프링 내에서 특정한 객체(빈)을 찾기 위해서 사용하는 일종의 가명이다.
뒤에 이 속성의 값을 이용해서 다른 객체와 연결하는 모습을 볼 수 있다.
DataSource의 테스트 진행
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}) public class DataSourceTest { @Inject private DataSource ds; @Test public void testConnection()throws Exception{ try(Connection con = ds.getConnection()) { System.out.println(con); } catch(Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
클래스 선언 맨 위에 있는 @RunWith, @ContextConfiguration 어노테이션은 현재 테스트 코드를 실행할 때 스프링이 로딩되도록 하는 부분이다. @ContextConfiguration의 속성 locations 속성 경로에 xml 파일을 이용해서 스프링이 로딩된다. 인스턴스 변수의 @Inject 어노테이션 처리된 DataSource는 스프링이 생성해서 주입해 주므로 개발자가 객체 생성 혹은 다른 작업을 하지 않아도 된다.
SqlSessionFactory 객체 설정
MyBatis와 스프링 연동작업에서의 핵심은 Connection을 생성하고, 처리하는 SqlSessionFactory의 존재이다.
SqlSessionFactory는 데이터베이스와의 연결과 SQL의 실행에 대한 모든 것을 가진 가장 중요한 객체이다.
스프링을 이용할 때는 SqlSessionFactory를 생성해 주는 특별한 객체를 설정해 주는데 SqlSessionFactoryBean이라는 클래스를 사용한다. root-context.xml을 이용해서 다음과 같이 등록한다.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>
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>
스프링이 동작할 때 같이 동작하도록 설정해주는 작업을 해야한다.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:/mybatis-config.xml"></property> </bean>
MyBatis의 연결 테스트
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}) public class MyBatisTest { @Inject private SqlSessionFactory sqlFactory; @Test public void testFactory() { System.out.println(sqlFactory); } @Test public void testSession()throws Exception{ try(SqlSession session = sqlFactory.openSession()) { System.out.println(session); } catch(Exception e) { e.printStackTrace(); } } }
myBatis-Spring에서 XML Mapper 인식
root-context.xml
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:/mybatis-config.xml"/> <property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"/> </bean>
mapperLocations라는 속성에서 mappers폴더 내에 어떤 폴더이건 관계없이 파일의 이름이 'Mapper.xml'로 끝나면 자동으로 인식하도록 설정
MyBatis에서 DAO를 이용하는 경우넨 SqlSessionTemplate이라는 것을 이용해 DAO를 구현하므로, 우선적으로 SqlSessionTemplate를 설정하는 작업을 해야한다.
작업이 완결된 후에 연결을 close()해줌
sqlSession인터페이스를 구현한 클래스로 기본적인 트랜잭션의 관리나 쓰레드 처리의 안정성 들을 보장해 주고, 데이터베이스의 연결과 종료를 책입해준다.
root-context.xml
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean>
스프링이 해당패키지를 스캔하도록 스프링의 빈으로 등록한다.
root-context.xml
<context:component-scan base-package="org.zerock.persistence"/>
아이콘을 확인하자
테스트코드작성
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}) public class MemberDAOTest { @Inject private MemberDAO dao; @Test public void testTime()throws Exception { System.out.println(dao.getTime()); } @Test public void testInserMember()throws Exception{ MemberVO vo = new MemberVO(); vo.setUserid("user00"); vo.setUserpw("user00"); vo.setUsername("USER00"); vo.setEmail("user00@aaa.com"); dao.insertMember(vo); } }
'스프링 프레임워크' 카테고리의 다른 글
get과 post방식 (0) 2019.05.01 스프링의 UTF-8 처리 필터 등록 (0) 2019.05.01 JDBC 연결을 위한 porm.xml파일의 수정과 테스트 코드 (0) 2019.04.28 jUnit을 이용한 테스트 작업 (0) 2019.04.28 스프링 프레임워크의 특징 (0) 2019.04.28