MyBatis is one of the most commonly used open-source frameworks for implementing SQL databases access in Java applications.

In this quick tutorial, we’ll present how to integrate MyBatis with Spring and Spring Boot.

If you are using maven include the following dependencies.

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>

We will be using annotation-based configurations for this example.

The only required elements are Datasource and SqlSessionFactory and at least one mapper file.

You can specify both in application.yml file as shown below

spring:
  ## Datasoruce
  datasource:
    url: ''
    username: ''
    password: ''
    driverClassNames: oracle.jdbc.OracleDriver
mybatis:
  typeAliasesPackage: //path to mapper files
  configuration:
    map-underscore-to-camel-case: true
    jdbcTypeForNull: VARCHAR
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Our final step is to create mapper file

public interface ArticleMapper 
{ 
  @Select("SELECT * FROM ARTICLES WHERE id = #{id}") 
  Article getArticle(@Param("id") Long id); 
}

Now we can test our setup

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class ArticleMapperIntegrationTest {

    @Autowired
    ArticleMapper articleMapper;

    @Test
    public void whenRecordsInDatabase_shouldReturnArticleWithGivenId() {
        Article article = articleMapper.getArticle(1L);

        assertThat(article).isNotNull();
        assertThat(article.getId()).isEqualTo(1L);
        assertThat(article.getAuthor()).isEqualTo("Baeldung");
        assertThat(article.getTitle()).isEqualTo("Working with MyBatis in Spring");
    }
}