스프링 프레임워크/스프링 기본 개념 정리 및 기본 예제

Spring MVC - Mybatis 설정 및 테스트

edenDev 2023. 2. 9.

Spring MVC - Mybatis 설정 및 테스트

본 포스팅의 예제는 STS(Spring Tool Studio) 또는 Eclipse를 사용하지 않고 intellij를  통해 구현하고 있습니다.

그래서 기존의 생성된 STS(Spring Tool Studio) 생성된 Spring 프로젝트의 스프링 설정 파일명과 프로젝트 구조가

약간 다를 수 있습니다. Intellij 스프링 mvc 프로젝트 생성 포스팅을 참고해주시면 감사하겠습니다.


1. Mybatis의 장점 간단 요약

  • 간결한 코드 처리 : JDBC 작업을 위한 반복적인 코드( try~catch~finally, PreparedStatement, RequestSet ) 을 직접 작성 하지 않아도 된다.
  • SQL문 분리 운영 : XML 또는 어노테이션 방식으로 SQL문을 별도로 처리하는 작업이 가능하다.
  • Spring과 연동으로 자동화된 처리 : Mybatis-Spring 라이브러리를 이용하여 직접 SQL문 호출 없이도 원하는 결과를 얻을 수 있다.
  • 동적 SQL을 이용한 제어 기능 : 제어문이나 반복문 등의 처리 기능을 통해 SQL과 관련된 처리를 Java코드에서 분리할 수 있다.

2. Mybatis 연동을 위한 설정

pom.xml에 JDBC, Mybatis관련 라이브러리를 추가해주세요.

        <!-- Mybatis 라이브러리 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
 
        <!-- Mybatis Spring 라이브러리 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
 
        <!-- Spring Test 라이브러리 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
 
        <!-- Spring JDBC 라이브러리 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
cs

applicationContext.xml에 DataSource 설정을 작성해주세요.

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
        <property name="url" value="jdbc:mariadb://svc.gksl2.cloudtype.app:30708/eden"/>
        <property name="username" value="eden"/>
        <property name="password" value="eden"/>
    </bean>
cs

3. DataSource 테스트

test/java/하위 패키지에 아래와 같이 테스트 코드를 작성해 주세요.

package com.eden.euphoria;
 
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 javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/applicationContext.xml"})
public class DataSourceTest {
 
    @Autowired
    private DataSource dataSource;
 
    @Test
    public void testConnection() throws Exception {
        try (Connection connection = dataSource.getConnection()) {
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
cs

테스트 코드를 실행시켜 정상적으로 테스트가 완료되면 콘솔에 아래와 같이 출력됩니다.

2023-02-09 05:26:17,822 INFO  [main] support.DefaultTestContextBootstrapper (AbstractTestContextBootstrapper.java:248)     - 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]
2023-02-09 05:26:17,876 INFO  [main] support.DefaultTestContextBootstrapper (AbstractTestContextBootstrapper.java:177)     - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@6ad82709, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@510f3d34, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@7817fd62, org.springframework.test.context.support.DirtiesContextTestExecutionListener@8297b3a, org.springframework.test.context.transaction.TransactionalTestExecutionListener@2362f559, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@b2c9a9c, org.springframework.test.context.event.EventPublishingTestExecutionListener@4c178a76]
org.mariadb.jdbc.Connection@48f5bde6
 
cs

4. Mybatis 연결 설정

applicationContext.xml에 SqlSessionFactory 객체를 설정해 주세요

    <!-- mybatis SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:/mybatis-config.xml"/>
    </bean>
cs

mybatis-config.xml은 Mybatis 설정파일로 src/main/rsources 디렉토리에 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>
    <typeAliases>
    </typeAliases>
</configuration>
cs

5. Mybatis 연결 테스트

test/java/하위 패키지에 아래와 같이 테스트 코드를 작성해 주세요.

package com.eden.euphoria;
 
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;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/applicationContext.xml"})
public class MybatisTest {
 
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
 
    @Test
    public void testFactory() {
        System.out.println(sqlSessionFactory);
    }
 
    @Test
    public void testSession() throws Exception {
        try(SqlSession session = sqlSessionFactory.openSession()) {
            System.out.println(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
cs

테스트 코드를 실행시켜 정상적으로 테스트가 완료되면 콘솔에 아래와 같이 출력됩니다.

2023-02-09 05:33:17,090 INFO  [main] support.DefaultTestContextBootstrapper (AbstractTestContextBootstrapper.java:248)     - 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]
2023-02-09 05:33:17,131 INFO  [main] support.DefaultTestContextBootstrapper (AbstractTestContextBootstrapper.java:177)     - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@b2c9a9c, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@4c178a76, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@fa4c865, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3bd82cf5, org.springframework.test.context.transaction.TransactionalTestExecutionListener@544fa968, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@247bddad, org.springframework.test.context.event.EventPublishingTestExecutionListener@d35dea7]
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@7e809b79
org.apache.ibatis.session.defaults.DefaultSqlSession@3e2943ab
cs

 

댓글