티스토리 뷰

Programming/Spring

[Spring] MyBatis 연동

@워너 2017.12.15 15:41



테스트 환경

OS : Windows 10 64bit

Spring : 4.1.7.RELEASE

Java : 1.8



1. pom.xml에 프레임워크, 라이브러리 추가


<!-- MyBatis -->

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.2.8</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.2.2</version>

</dependency>


<!-- Spring -->

<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>




2. root-context.xml 

 - src/main/webapp/WEB-INF/spring/root-context.xml

 - root-context.xml 하단 Namespaces 탭 선택



 - XML 네임스페이스 추가 확인


<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"

xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd

http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">




3. root-context.xml에 DataSource 추가


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql://xxx.xxx.xxx.xxx:3306/testDB"></property>

<property name="username" value="test"></property>

<property name="password" value="testpass"></property>

</bean>




4. DataSource 연결 테스트 


 - @RunWith, @ContextConfiguration 애노테이션은 테스트 코드를 실행할 때 스프링이 로딩 되도록 한다.

 - location 속성 경로에 xml 파일을 이용해서 스프링이 로딩 된다.


DataSourceTest.java


package org.zerock.web;


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(

locations = {"file:src/main/webapp/WEB-INF/spring/**/*.xml"})

public class DataSourceTest {

@Inject

private DataSource dataSource;

@Test

public void testConection() throws Exception{

try (Connection con = dataSource.getConnection()){

System.out.println(con);

} catch (Exception e) {

System.err.println(e);

}

}

}



Run As -> JUnit Test 실행




5. Mybatis 연결

 - SqlSessionFactory 객체 설정 : 데이터베이스와의 연결과 SQL의 실행에 대한 모든 것을 가진 객체

 

 a. root-context.xml에 다음 bean 추가

 

<!-- MyBatis -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

</bean>



 b. mybatis-config.xml 파일 생성 및 수정

  - src/main/resources/mybatis-config.xml


<?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>



 c. root-context.xml 수정

  - 스프링이 동작할 때 mybatis-config.xml 파일이 같이 동작하도록 설정

  

<!-- MyBatis -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="configLocation" value="classpath:/mabatis-config.xml"></property>

</bean>


 

 d. MyBatis 연결 테스트 소스 코드


package org.zerock.web;


import javax.inject.Inject;


import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

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(locations = {"file:src/main/webapp/WEB-INF/spring/**/*.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) {

System.err.println(e);

}

}

}




- SqlSession 생성이 제대로 되었는지 확인. 



* 참조 : 코드로 배우는 스프링 웹 프로젝트




# driverClassName 관련 에러 발생 시 적용

 - pom.xml 라이브러리 추가


<dependency>

<groupId>commons-dbcp</groupId>

<artifactId>commons-dbcp</artifactId>

<version>1.4</version>

</dependency>



 - root-context.xml에 DataSource 수정


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="com.mysql.jdbc.Driver"/>

      <property name="url" value="jdbc:mysql://xxx.xxx.xxx.xxx:3306/testDB"></property>

      <property name="username" value="test"></property>

      <property name="password" value="testpass"></property>

</bean>


댓글