MyBatis | Integration with Spring Boot

Because a plugin for Spring Boot is included, it can be integrated easily by using it.

DB Table

test_table

id value
1 hoge
2 fuga
3 piyo

Folder Structure

├── build.gradle
├── src/main/
│   └── java/
│   └── sample/mybatis/springboot/
│       └── Main.java
│       └── TestTableMapper.java
└── resources/
    └── application.properties
    └── mybatis-config.xml
    └── TestTableMapper.xml

Source Code

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE'
    }
}

apply plugin: 'java'
apply plugin: 'spring-boot'

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
compileJava.options.encoding = 'UTF-8'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter'
    // Include the dependency library file for MyBatis Spring Boot.
    compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.0.0'
    compile 'mysql:mysql-connector-java:5.1.38'
}

application.properties

# Load the MyBatis configuration file.
mybatis.config=mybatis-config.xml

# Configure the data source.
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

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>
 <!-- Data source management is handled by Spring Boot, so it is not written here. -->
  <mappers>
    <mapper resource="TestTableMapper.xml"/>
  </mappers>
</configuration>

TestTableMapper.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="sample.mybatis.springboot.TestTableMapper">

  <select id="selectTest" resultType="map">
    select * from test_table
  </select>
</mapper>

TestTableMapper.java

package sample.mybatis.springboot;

import java.util.List;
import java.util.Map;

public interface TestTableMapper {

    List<Map<String, Object>> selectTest();
}

Main.java

package sample.mybatis.springboot;

import java.io.IOException;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Main {

    public static void main(String[] args) throws IOException {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
            Main m = ctx.getBean(Main.class);
            m.method();
        }
    }

    @Autowired
    private SqlSessionTemplate sqlSession;
    @Autowired
    private TestTableMapper mapper;

    public void method() throws IOException {
        System.out.println("[SqlSessionTemplate]");
        this.sqlSession
            .selectList("sample.mybatis.springboot.TestTableMapper.selectTest")
            .forEach(System.out::println);

        System.out.println("[TestTableMapper]");
        this.mapper
            .selectTest()
            .forEach(System.out::println);
    }
}

Execution Result

[SqlSessionTemplate]
{id=1, value=hoge}
{id=2, value=fuga}
{id=3, value=piyo}

[TestTableMapper]
{id=1, value=hoge}
{id=2, value=fuga}
{id=3, value=piyo}

Description

  • When using MyBatis with Spring Boot, add mybatis-spring-boot-starter as a dependency.
  • Next, specify the MyBatis configuration file with the name mybatis.config in the Spring Boot configuration file (application.properties).
  • Because the data source is managed by Spring Boot, configure it in the Spring Boot settings and do not define it separately in MyBatis.
  • To access SqlSession, inject SqlSessionTemplate with @Autowired.
    • The API of SqlSessionTemplate is the same as SqlSession.
    • Unlike SqlSession, it is thread-safe, so it can be used from other threads or DAOs without issue.
  • If you define a Mapper interface, it can be injected with @Autowired.
    • Place the interface in a location scanned by Spring.
    • If you annotate the Main class with @MapperScan, you can scan Mapper interfaces in all packages, for example @MapperScan("foo.bar").
    • This also injects a thread-safe instance, so it can be used from other threads or DAOs without issue.