How do I create MyBatis mapper?

In this example you will see how to create or define a data mapper using the MyBatis. The mapper will communicate our application with the underlying databases where the data is stored. MyBatis data mapper is defined as an interface object. We can either use annotations or the xml mapper to define our database query.

In the first steps we will create a domain object, a simple pojo to store our data in the object world. The attributes / fields of our pojo resemble the structure of our records table in the database.

package org.kodejava.mybatis.support;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Long id;
    private String title;
    private Date releaseDate;
    private Long artistId;
    private Long labelId;

    // Getters & Setters

    @Override
    public String toString() {
        return "Record{" +
            "id=" + id +
            ", title='" + title + '\'' +
            ", releaseDate=" + releaseDate +
            ", artistId=" + artistId +
            ", labelId=" + labelId +
            '}';
    }
}

Next we define the mapper interface code, we’ll create a RecordMapper.java file that contains a method to get data from the table. At this time the interface will be as the following:

package org.kodejava.mybatis;

import org.kodejava.mybatis.support.Record;

public interface RecordMapper {
    /**
     * Get a single Record from the database based on the record
     * identified.
     * 
     * @param id record identifier.
     * @return a record object.
     */
    Record getRecord(Long id);
}

After create the ResultMapper.java interface we create a RecordMapper.xml file that defines the queries used by our mapper. Here is how it looks like:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.kodejava.mybatis.RecordMapper">

    <resultMap id="recordResultMap" type="record">
        <result column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="release_date" property="releaseDate"/>
        <result column="artist_id" property="artistId"/>
        <result column="label_id" property="labelId"/>
    </resultMap>

    <select id="getRecord" parameterType="java.lang.Long" resultMap="recordResultMap">
        SELECT id,
            title,
            release_date,
            artist_id,
            label_id
        FROM record
        WHERE id = #{id}
    </select>
</mapper>

To tell MyBatis about our mapper we need to define the mapper inside MyBatis configuration file (resources/configuration.xml). We register the mapper inside the <mappers> element of the configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="record" type="org.kodejava.mybatis.support.Record" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost/musicdb" />
                <property name="username" value="music" />
                <property name="password" value="s3cr*t" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/mybatis/mapper/RecordMapper.xml" />
    </mappers>
</configuration>

Finally, we create a simple application to use the data mapper to get record data from the database.

package org.kodejava.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.kodejava.mybatis.support.Record;

import java.io.Reader;

public class MusicClient {

    public static void main(String[] args) throws Exception {
        Reader reader = Resources.getResourceAsReader("configuration.xml");

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(reader);

        try (SqlSession session = factory.openSession()) {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Record record = mapper.getRecord(1L);
            System.out.println("Record = " + record);
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Wayan

1 Comments

  1. I am using mybatis-spring-boot-starter version 2.0.1 for a Vaadin 13.0.3 project.

    The documentation for MyBatis says “When using MyBatis with a dependency injection framework like Spring or Guice, SqlSessions are created and injected by the DI framework so you don’t need to use the SqlSessionFactoryBuilder or SqlSessionFactory and can go directly to the SqlSession section. Please refer to the MyBatis-Spring or MyBatis-Guice manuals for further info.”

    Can you show me what would be different in the case of using Spring Boot? For example, how would the Application part be different. I’m assuming Spring Boot has a class providing a SqlSession but I don’t know how to connect it to everything else. I began my project by using annotations but due to needing conditional SQL statements I an trying to change it to XML. Thank you in advance for any help.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.