okutane okutane - 6 days ago 5
Java Question

mybatis - fetching lists of properties for list of objects

Suppose I have following dto classes:

class Item {
int id;
List<Detail> details;

public String toString() {
return "{id: " + id + ", details: " + details + "}";

class Detail {
String name;
String value;

public String toString() {
return "{" + name + ": " + value + "}";

Is it possible to write a mapper xml to retrieve list of Items with properly filled Details and all the data will be retrieved with two queries (1st for items, 2nd for details). In the example below there will be N+1 queries (N - number of items).

Complete example (for sample schema, test data and usage)


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.sql.*;
import java.sql.Statement;
import java.util.List;

public class Sandbox {
public static void main(String... args) throws Throwable {
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("drop table if exists Item");
statement.executeUpdate("create table Item (id integer)");

statement.executeUpdate("insert into Item values(1)");
statement.executeUpdate("insert into Item values(2)");

statement.executeUpdate("drop table if exists Detail");
statement.executeUpdate("create table Detail (id integer, name string, value string)");

statement.executeUpdate("insert into Detail values(1, 'name', 'foo')");
statement.executeUpdate("insert into Detail values(1, 'purpose', 'test')");
statement.executeUpdate("insert into Detail values(2, 'name', 'bar')");

SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));

try (SqlSession session = sqlSessionFactory.openSession()) {
MyMapper mapper = session.getMapper(MyMapper.class);
List<Item> items = mapper.selectItems();

System.out.println("items = " + items);


import java.util.List;

public interface MyMapper {
List<Item> selectItems();


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<mapper namespace="MyMapper">
<resultMap id="ItemMap" type="Item">
<id column="id" property="id"/>
<collection column="id" property="details" select="selectDetails"/>

<select id="selectItems" resultMap="ItemMap">
select * from Item

<select id="selectDetails" parameterType="int" resultType="Detail">
select * from Detail WHERE id=#{id}


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="net.sf.log4jdbc.DriverSpy"/>
<property name="url" value="jdbc:log4jdbc:sqlite:sample.db"/>
<mapper resource="Mapper.xml"/>


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">






Pau Pau

If you take a look the section Multiple ResultSets for Association in Mappers XML of the reference documentation it is explained:

Starting from version 3.2.3 MyBatis provides yet another way to solve the N+1 problem.

Some databases allow stored procedures to return more than one resultset or execute more than one statement at once and return a resultset per each one. This can be used to hit the database just once and return related data without using a join.

There is an example with this. So you would need a stored procedure with queries:

select * from Item
select * from Detail WHERE id=#{id}

Then the select will call the stored procedure as next:

<select id="selectItems" resultSets="item,details" resultMap="ItemMap">
  {call getItemAndDetails(#{id,jdbcType=INTEGER,mode=IN})}

Finally the resultmap:

specify that the "details" collection will be filled out of data contained in the result set named "details"

Your collection tag in the result map would be something as next:

<collection property="details" ofType="Detail" resultSet="details" column="id" foreignColumn="foreign_id">