본문으로 바로가기

[Spring] 스프링, MySQL, MyBatis 연동

category 코딩/Spring 2017. 8. 6. 14:31







스프링, MySQL, MyBatis 연동



프로젝트 생성 및 관련 설정들은 아래 글을 참고하면 된다.






프로젝트 생성 후 pom.xml을 연다. 여기에 연동에 필요한 라이브러리를 설정할 것이다.





pom.xml 에서  <dependencies></dependencies> 태그 사이에 MySQL 및 MyBitis 관련 라이브러리를 설정한다.


  • MySQL : MySQL 라이브러리

  • MyBitis 3.4.1 : MyBitis 프레임워크

  • MyBitis-Spring : Spring과 MyBitis를 연결하는 라이브러리

  • Spring-jdbc : jdbc 라이브러리

  • Spring-test : 스프링과 MyBitis가 정상적으로 연동되었는지 확인하기 위해 필요한 라이브러리


        
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
 
        <!-- MyBatis 3.4.1 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
 
 
        <!-- MyBatis-Spring -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
 
        <!-- Spring-jdbc -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
 
        <!-- Spring-test -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>





■ Maven Dependency 라이브러리 사이트





다음으로 pom.xml 위쪽을 보면 junit dependency 가 있다. 여기서 버전을 4.12로 변경하자. junit은 MySQL 및 MyBitis가 정상적으로 연동되었는지 테스트하기 위해 필요하다.





다음으로 root-context.xml을 연다. root-context.xml은 웹과 관련되지 않은 자원들에 대한 설정을 입력하는 곳이다.  이곳에는 MySQL 및 MyBitis에 대한 설정을 할 것이다.





먼저 하단 Namespaces 탭을 클릭한다.





위와 동일하게 체크한다. 이것은 사용 가능한 XML 태그의 폭을 넓혀주기 위한 설정이다.





다시 root-context.xml의 Source로 돌아온다. 여기에는 DataSource와 SqlSessionFactoryBean을 설정한다.


DataSource는 MySQL과 연결을 담당한다. DataSource는 JDBC 커넥션을 처리하는 기능을 가지고 있기에 DB와 연동하는 작업에 반드시 필요하다.



 
    <!-- MySQL dataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://데이터베이스 주소:포트번호/스키마이름?useSSL=false&amp;serverTimezone=UTC">
</property>
        <property name="username" value="MySQL 계정"></property>
        <property name="password" value="비밀번호"></property>
    </bean>        
        
 
 
    <!-- 자신의 PC(로컬)에 MySql을 설치했을 경우 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://127.0.0.1:3306/스키마이름?useSSL=false&amp;serverTimezone=UTC">
</property>
        <property name="username" value="MySQL 계정"></property>
        <property name="password" value="비밀번호"></property>
    </bean>        
 



DataSource 에는 여러 개의 property가 있는데 여기서는 연결할 DB의 주소, 계정, 비밀번호 이렇게 3개의 property만 설정하면 된다. 연결 주소에는 로컬일 경우  127.0.0.1을 입력하고 뒤에는 3306을 입력한다. 3306은 MySQL 설치시 지정한 포트인데, 별도로 변경하지 않았다면 3306이 기본 포트이다. 


그 뒤에는 스키마 이름을 입력한다. 스키마 이름은 MySQL 설치 후 신규 계정을 만들 때 생성하는데 아래의 글을 참고하면 된다.





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


 

SqlSessionFactoryBean는 DB와의 연결과 SQL의 실행에 대한 모든 것을 가진 객체이다. 일단은 간단히 연동 테스트만 할 것이므로 위와 같이 입력하면 된다. 나중에 DB에 연결해 데이터를 저장, 수정, 삭제, 조회 할 경우 별도의 추가 설정을 할 것이다.





root-context.xml 까지 작업을 했으면 src/test/java 를 보자. 여기에 보면 패키지 하나가 생성되어 있는데, 거기에다 MySQLConnectionTest 와 MyBatisTest 라는 클래스를 생성한다. 각각 MySQL 연결, MyBatis 연결을 테스트 하기 위한 클래스이다.



■ MySQLConnectionTest.java


package com.sample.mybatis;
 
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/**/root-context.xml" })
public class MySQLConnectionTest {
    
    @Inject
    private DataSource ds;
 
    @Test
    public void testConnection() throws Exception {
 
        try (Connection con = ds.getConnection()) {
 
            System.out.println("\n >>>>>>>>>> Connection 출력 : " + con + "\n");
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}




■ MyBatisTest.java


package com.sample.mybatis;
 
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/**/root-context.xml"})
public class MyBatisTest 
{
    @Inject
    private SqlSessionFactory sqlFactory;
    
    @Test
    public void testFactory(){
        System.out.println("\n >>>>>>>>>> sqlFactory 출력 : "+sqlFactory);
    }
    
    @Test
    public void testSession() throws Exception{
        
        try(SqlSession session = sqlFactory.openSession()){
            
            System.out.println(" >>>>>>>>>> session 출력 : "+session+"\n");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
 




소스 코드가 정상적으로 동작하면 MySQLConnectionTest 클래스는 Connection을, MyBatisTest 클래스는 SqlSessionFactory와 SqlSession의 주소를 출력할 것이다.





테스트를 위해 MySQLConnectionTest 를 마우스 우클릭한다. 그리고 [Run As] - [Junit Test] 를 선택한다.





정상적으로 실행되면 위와 같이 출력이 된다.





마찬가지로 MyBatisTest 도 정상 실행되면 위와같이 출력이 될 것이다. 




여기까지가 Spring, MySQL, MyBatis의 간단한 연동이다. 여기에서는 단순히 연동에 대한 테스트만 했으므로, 쿼리를 작성하고 DB에 데이터를 조회하거나 입력하는 작업을 하려면 추가적인 작업이 필요하다. 




소스 코드 다운로드



Spring_EX_01.zip



RSS구독 링크추가 트위터 이메일 구독