MyBatis | Mapper | Basics

DB table

test_table

id string number
1 hoge 100
2 fuga 200
3 piyo 300

Source code

TestTable.java

package sample.mybatis;

public class TestTable {
    private int id;
    private String string;
    private int number;

    @Override
    public String toString() {
        return "TestTable [id=" + id + ", string=" + string + ", number=" + number + "]";
    }
}

sample_mapper.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.TestTableMapper"> <!-- Use the Mapper FQCN as the namespace. -->

  <select id="selectAll" resultType="sample.mybatis.TestTable">
    select *
      from test_table
  </select>
</mapper>

TestTableMapper.java

package sample.mybatis;

import java.util.List;

// Mapper interface
public interface TestTableMapper {

    // Define a method with the same name as the statement ID.
    List<TestTable> selectAll();
}

Main.java

package sample.mybatis;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

            try (SqlSession session = factory.openSession()) {
                // Get a Mapper instance.
                TestTableMapper mapper = session.getMapper(TestTableMapper.class);

                mapper.selectAll().forEach(System.out::println);
            }
        }
    }
}

Execution result

[DEBUG] s.m.T.selectAll - ==>  Preparing: select * from test_table 
[DEBUG] s.m.T.selectAll - ==> Parameters: 
[DEBUG] s.m.T.selectAll - <==      Total: 3
TestTable [id=1, string=hoge, number=100]
TestTable [id=2, string=fuga, number=200]
TestTable [id=3, string=piyo, number=300]

Explanation

  • When using a Mapper, define a dedicated interface (TestTableMapper).
    • Define each method so that it corresponds to each statement in the configuration file.
    • In the statement, set namespace to the FQCN of the interface (sample.mybatis.TestTableMapper).
    • Match the statement ID with the method name in the interface (selectAll).
    • If parameters exist, define the method so that arguments are passed to it.
  • Obtain a Mapper instance with the getMapper() method of SqlSession.