MyBatis | Mapping Query Results to Arbitrary Java Objects | Collection Mapping
Basic usage
DB tables
foo_table
| id |
|---|
| 1 |
| 2 |
| 3 |
bar_table
| key1 | foo_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 3 |
Source code
Foo.java
package sample.mybatis;
import java.util.List;
public class Foo {
private int id;
private List<Bar> barList;
@Override
public String toString() {
return "Foo [id=" + id + ", barList=" + barList + "]";
}
}
Bar.java
package sample.mybatis;
public class Bar {
private int id;
@Override
public String toString() {
return "Bar [id=" + id + "]";
}
}
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">
<resultMap type="sample.mybatis.Foo" id="fooResultMap">
<id property="id" column="id" />
<!-- Use the collection tag. -->
<collection property="barList" ofType="sample.mybatis.Bar">
<id property="id" column="bar_id" />
</collection>
</resultMap>
<select id="selectFoo" resultMap="fooResultMap">
select foo.id
,bar.id bar_id
from foo_table foo
,bar_table bar
where bar.foo_id = foo.id
</select>
</mapper>
Execution result of selectFoo
[DEBUG] s.m.selectFoo - ==> Preparing: select foo.id ,bar.id bar_id from foo_table foo ,bar_table bar where bar.foo_id = foo.id
[DEBUG] s.m.selectFoo - ==> Parameters:
[DEBUG] s.m.selectFoo - <== Total: 6
Foo [id=1, barList=[Bar [id=1], Bar [id=2], Bar [id=3]]]
Foo [id=2, barList=[Bar [id=4], Bar [id=5]]]
Foo [id=3, barList=[Bar [id=6]]]
Explanation
- Use the
<collection>tag to map a collection. - Specify the type of each element with the ofType attribute. Aliases can also be used.
- Otherwise, configure it in the same way as the
<association>tag.