본문 바로가기

Backend/Spring

스프링 - 마이바티스 설정 (MySQL)

Update

- 2022.04.09 : springboot / spring framework 설정방식 구분


 

MyBatis란?

마이바티스는 개발자가 작성한 SQL 구문을 손쉽게 실행하고 결과를 조회할 수 있도록 돕는 프레임워크입니다.

 

 

필수 인터페이스

스프링에서 MyBatis를 사용하기 위해서는 SqlSessionFactory와 1개 이상의 Mapper 인터페이스가 필요합니다. 

 

 

Intro

SqlSessionFactory가 생성하는 SqlSession이란?

> DataBase에 SQL을 실행하기 위해 필요한 객체입니다.

 

MyBatis에서 SQL 구문은 SqlSession을 통해 실행되며 쓰레드마다 별도의 SqlSession 인스턴스를 가집니다.

(SqlSession 인스턴스는 쓰레드간 공유되지 않습니다.) SqlSession의 생명주기는 client 요청시 생성되고 역할을 수행한 뒤 소멸합니다. (SqlSessionFactory는 싱글턴 형태로 단 한개만 생성되며 어플리케이션이 실행되고 있는 동안 존재합니다.)

 

 

 

SqlSessionFactory 설정하기

 

SqlSessionFactory는 SqlSessionFactoryBean 구현체를 활용하여 생성하고 DataSource를 주입받습니다.

(순수 MyBatis 프레임워크만 이용할 경우에는 SqlSessionFactoryBuilder를 사용하지만 Spring에서 MyBatis를 셋팅할 경우 SqlSessionFactoryBean을 사용합니다.)

 

쿼리를 수행할 때 필요한 설정정보 (매퍼 위치, alias 지정 등)를 설정하는 방법은 외부파일(xml)을 읽어오거나 설정객체 (org.apache.ibatis.session.Configuration)를 활용해서 설정가능합니다.

 

 

<MyBatis-spring>

 

Configuration 클래스

@Configuration
@MapperScan(basePackages = "com.example.mybatis", annotationClass = org.springframework.stereotype.Repository.class)
public class MybatisConfig {


    @Bean
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("com.mysql.cj.jdbc.Driver");
        dataSourceBuilder.url("jdbc:mysql://localhost:3306/mybatis_test?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Seoul");
        dataSourceBuilder.username("username");
        dataSourceBuilder.password("password");

        return dataSourceBuilder.build();
    }

    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/**/*.xml"));
        factoryBean.setTypeAliasesPackage("com.example.mybatis");
        return factoryBean.getObject();
    }

    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

 

 

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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

 

 

 

 

<MyBatis-springboot>

 

Springboot

mybatis 역시 다른 스프링부트 어플리케이션처럼 application.properties(or application.yml)을 통해 값을 설정할 수 있습니다.

 

(@Configuration 클래스를 통해 빈을 생성하지 않아도 application 설정파일을 읽어 빈을 생성하여 등록해줍니다.)

 

application.properties 설정값

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_test?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Seoul
spring.datasource.username=username
spring.datasource.password=password

mybatis.type-aliases-package=com.example.springboot
mybatis.mapper-locations=classpath:/mapper/**/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

 

 

 

Mapper 인터페이스 생성하기

 

MapperScan의 annotationClass 속성을 이용해서 원하는 어노테이션으로 Mapper Interface를 설정할 수 있다.

xml 파일의 namespace는 mapper interface 의 풀네임으로 해야하고 xml에 작성한 SQL 구문의 id 값으로 interface의 메서드 이름을 작성한다.

 

Mapper Scan

@Configuration
@MapperScan(basePackages = "com.example.mybatis", annotationClass = org.springframework.stereotype.Repository.class)
public class MybatisConfig {
	...
}

 

Mapper 인터페이스

//@Mapper
@Repository
public interface BasicDao {
    List<User> selectAll();
}

xml 파일

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mybatis.dao.BasicDao">
    <select id="selectAll" resultType="user">
        select * from user
    </select>
</mapper>

 

 

 

샘플코드는 아래 Git 주소를 확인해주세요.

 

spring 설정방식 - https://github.com/JaewookMun/spring-exercise/tree/main/mybatis/spring-framework

 

GitHub - JaewookMun/spring-exercise: 스프링 연습 https://spring.io/guides

스프링 연습 https://spring.io/guides. Contribute to JaewookMun/spring-exercise development by creating an account on GitHub.

github.com

 

springboot 설정방식 - https://github.com/JaewookMun/spring-exercise/tree/main/mybatis/springboot

 

GitHub - JaewookMun/spring-exercise: 스프링 연습 https://spring.io/guides

스프링 연습 https://spring.io/guides. Contribute to JaewookMun/spring-exercise development by creating an account on GitHub.

github.com

 

 

 

 

 

[참고]

MyBatis Official : https://mybatis.org/mybatis-3/ko/getting-started.html

 

MyBatis – 마이바티스 3 | 시작하기

Copyright © 2009–2021MyBatis.org. .

mybatis.org

 

MyBatis - Spring Official : https://mybatis.org/spring/ko/getting-started.html

 

mybatis-spring –

시작하기 이 장은 마이바티스 스프링 연동모듈을 설치하고 셋팅하는 방법에 대해 간단히 보여준다. 그리고 트랜잭션을 사용하는 간단한 애플리케이션을 만드는 방법까지 다룰 것이다. 설치 마

mybatis.org

 

MyBatis - SpringBoot  Official : https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ 

 

mybatis-spring-boot-autoconfigure – Introduction

Introduction What is MyBatis-Spring-Boot-Starter? The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the Spring Boot. By using this module you will achieve: Build standalone applications Reduce the boilerplate to almost z

mybatis.org