I'm rather new to MyBatis. There's theFoo
which could have many Bar
s, and the Bar
has fooId
as FK. I want to query for all Foo
s with its associated Bar
s.
Here are my domain objects:
public class Foo {
private int id;
private String name;
// key: Bar.id, value: Bar instance
private Map<Integer, Bar> bars;
// getter, setter etc
}
public class Bar {
private int id;
private int fooId;
private String model;
// getter, setter etc
}
The schema:
Foo | ||
---|---|---|
id | int | PK |
name | varchar |
Bar | ||
---|---|---|
id | int | PK |
fooId | varchar | FK |
model | varchar |
The result maps:
<resultMap id="selectBar" type="Bar">
<id property="id" column="id"/>
<result property="fooId" column="fooid"/>
<result property="model" column="model"/>
</resultMap>
<resultMap id="fooWithBars" type="Foo">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="bars" ofType="Bar" resultMap="Bar.selectBar" javaType="java.util.Map"/>
</resultMap>
The query:
<select id="selectFoos" resultMap="fooWithBars">
select F.name, F.id, B.id, B.fooId, B.model
from Foo P join Bar B on F.id = B.fooId
</select>
My question is how to map the collection to Map<Integer, Bar>? without using ResultHandler
The resultMap above apparently doesn't work. I also tried:
- nested resultMap which end up with collection of HashMaps instead of a collection in Hashmap, and there's no way of specifying the key to be the value of
Bar.id
- constructor injection which failed since Mybatis does not support use collection as an argumenthttps://github.com/mybatis/mybatis-3/issues/101
Thanks!