© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
K. S. P. Reddy, S. UpadhyayulaBeginning Spring Boot 3https://doi.org/10.1007/978-1-4842-8792-7_6

6. Working with MyBatis

Siva Prasad Reddy Katamreddy1   and Sai Subramanyam Upadhyayula2
(1)
Hyderabad, India
(2)
Rotterdam, The Netherlands
 

MyBatis is an open-source Java persistence framework that abstracts JDBC boilerplate code and provides a simple and easy-to-use API to interact with the database.

Unlike Hibernate , a full-blown ORM framework, MyBatis is a SQL mapping framework. It automates the process of populating the SQL resultset into Java objects, and it persists data into tables by extracting the data from the Java objects.

This chapter covers how to use the Spring Boot MyBatis starter, execute database queries using MyBatis XML, and use annotation-based mappers.

Using the Spring Boot MyBatis Starter

The MyBatis community built the Spring Boot starter for MyBatis, which you can use while creating the Spring Boot project from the Spring Initializer or the IDE. You can explore the source code on GitHub at https://github.com/mybatis/spring-boot-starter .

Let’s see how to use the Spring Boot MyBatis starter to quickly use MyBatis in Spring Boot applications.
  1. 1.

    Create a Spring Boot Maven project and configure the MyBatis Starter dependency and H2/MySQL driver dependencies .

     
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
This example reuses the User.java, schema.sql, and data.sql files created in the previous chapter.
  1. 2.

    Create the MyBatis SQL Mapper interface UserMapper.java with a few database operations, as shown in Listing 6-1.

     
package com.apress.demo.mappers;
public interface UserMapper
{
    void insertUser(User user);
    User findUserById(Integer id);
    List<User> findAllUsers();
}
Listing 6-1

com.apress.demo.mappers.UserMapper.java

  1. 3.

    You must create mapper XML files to define the queries for the SQL statements mapped to the corresponding mapper interface methods. Create the UserMapper.xml file in the src/main/resources/com/apress/demo/mappers/ directory, as shown in Listing 6-2.

     
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.apress.demo.mappers.UserMapper">
<resultMap id="UserResultMap" type="User">
    <id column="id"  property="id"  />
    <result column="name"  property="name"  />
    <result column="email"  property="email"  />
</resultMap>
<select id="findAllUsers" resultMap="UserResultMap">
        select id, name, email from users
</select>
<select id="findUserById" resultMap="UserResultMap">
        select id, name, email from users WHERE id=#{id}
</select>
<insert id="insertUser" parameterType="User" useGeneratedKeys="true"
            keyProperty="id">
        insert into users(name,email) values(#{name},#{email})
</insert>
</mapper>
Listing 6-2

src/main/resources/com/apress/demo/mappers/UserMapper.xml

A few things to observe here are the following:

  • The namespace in the mapper XML should be the same as the Fully Qualified Name (FQN) of the mapper interface.

  • The statement id values should be the same as the mapper interface method names.

  • Suppose the query result column names are different from the bean property names. If so, you can use the <resultMap> configuration to provide the mapping between column names and their corresponding bean property names.

  1. 4.

    MyBatis also provides annotation-based query configurations without requiring mapper XMLs. You can create the UserMapper.java interface and configure the mapped SQLs using annotations, as shown in Listing 6-3.

     
public interface UserMapper
{
    @Insert("insert into users(name,email) values(#{name},#{email})")
    @SelectKey(statement="call identity()", keyProperty="id",
                before=false, resultType=Integer.class)
    void insertUser(User user);
    @Select("select id, name, email from users WHERE id=#{id}")
    User findUserById(Integer id);
    @Select("select id, name, email from users")
    List<User> findAllUsers();
}
Listing 6-3

com.apress.demo.mappers.UserMapper.java

  1. 5.
    Next, you must configure the starter configuration parameters . Configure the type-aliases-package and mapper-locations parameters in application.properties as follows:
    mybatis.type-aliases-package=com.apress.demo.domain
    mybatis.mapper-locations=classpath*:/mappers/*.xml
     
  2. 6.

    Create the entry point class called SpringbootMyBatisDemoApplication.java, as shown in Listing 6-4.

     
@SpringBootApplication
@MapperScan("com.apress.demo.mappers")
public class SpringbootMyBatisDemoApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringbootMyBatisDemoApplication.class, args);
    }
}
Listing 6-4

com.apress.demo.SpringbootMyBatisDemoApplication.java

Note

This example uses the @MapperScan("com.apress.demo.mappers") annotation to specify where to look for the mapper interfaces. Instead of using @MapperScan, you could also use annotated mapper interfaces with the new @Mapper annotation that shipped with MyBatis 3.4.0.

  1. 7.

    Create a JUnit test class and test the UserMapper methods , as shown in Listing 6-5.

     
@SpringBootTest
public class SpringbootMyBatisDemoApplicationTests
{
    @Autowired
    private UserMapper userMapper;
    @Test
    public void findAllUsers()  {
        List<User> users = userMapper.findAllUsers();
        assertNotNull(users);
        assertTrue(users.isEmpty());
    }
    @Test
    public void findUserById()  {
        User user = userMapper.findUserById(1);
        assertNotNull(user);
    }
    @Test
    public void createUser() {
        User user = new User(0, "george", "[email protected]");
        userMapper.insertUser(user);
        User newUser = userMapper.findUserById(user.getId());
        assertEquals("george", newUser.getName());
        assertEquals("[email protected]", newUser.getEmail());
    }
}
Listing 6-5

com.apress.demo.SpringbootMyBatisDemoApplicationTests.java

The Spring Boot MyBatis starter provides the following MyBatis configuration parameters , which you can use to customize your MyBatis settings:
mybatis.config-location =  #mybatis config filename
mybatis.check-config-location=  # Indicates whether to perform presence check of the MyBatis xml config file
mybatis.mapper-locations =  #mappers file locations
mybatis.type-aliases-package =  #domain object's package
mybatis.type-handlers-package =  #handler's package
mybatis.check-config-location =  #check the mybatis configuration exists
mybatis.executor-type =  #mode of execution. Default is SIMPLE
mybatis.configuration-properties=  #externalized properties for mybatis configuration

You can read more about MyBatis at http://blog.mybatis.org/p/products.html and https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/ .

Summary

In this chapter, you learned how to work with MyBatis in Spring Boot applications. The next chapter covers how to use another popular Java persistence framework with Spring Boot, called JOOQ.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.39.142