MyBatis | Mapping Query Results to Arbitrary Java Objects | Basics

Data table

test_table

id value
1 fizz
2 buzz

Source code

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">
  <select id="selectTest" resultType="sample.mybatis.TestTable">
    select * from test_table
  </select>
</mapper>

TestTable.java

package sample.mybatis;

public class TestTable {

    private int id;
    private String value;

    public void setValue(String value) {
        System.out.println("setValue(" + value + ")");
        this.value = value;
    }

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

Main.java

package sample.mybatis;

import java.io.InputStream;
import java.util.List;

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()) {
                List<TestTable> result = session.selectList("sample.mybatis.selectTest");
                System.out.println(result);
            }
        }
    }
}

Execution result

[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table 
[DEBUG] s.m.selectTest  - ==> Parameters: 
setValue(fizz)
setValue(buzz)
[DEBUG] s.m.selectTest  - <==      Total: 2
[TestTable [id=1, value=fizz], TestTable [id=2, value=buzz]]

Explanation

  • Specify the Java class you want to map query results to in resultType.
  • Values are set on fields whose names match the column names.
  • If a setter method exists, values are set through it. Otherwise, they are set directly on the fields.