MyBatis | 検索結果を任意のJavaオブジェクトにマッピング | コレクションマッピング
基本
DBテーブル
foo_table
| id |
|---|
| 1 |
| 2 |
| 3 |
bar_table
| key1 | foo_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 3 |
ソースコード
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" />
<!-- collectionタグを使用する。 -->
<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>
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]]]
説明
- コレクションをマッピングするには
<collection>タグを使用する。 - 各要素の型はofType属性で指定する(別名も使用可能)。
- それ以外は
<association>タグの場合と同じ方法で設定する。