I would like to map data to java.util.Map attribute with MyBatis. I have simple POJOs like this:
public class Bar {
...fields
}
public class Foo {
private Map<String, Bar> bars;
public Foo() {
bars = new HashMap<String, Bar>();
}
...
}
How can I map data to bars with MyBatis? Example below doesn’t work because it sets always new map to field.
<resultMap id="fooResultMap" type="Foo">
...attributes
<association property="bars" resultMap="barResultMap" />
</resultMap>
<resultMap id="barResultMap" type="map">
<result property="key" column="bar_key" />
<association property="value" javaType="Bar">
...attributes
</association>
</resultMap>
I’ve done some research on this and asked on the MyBatis Google group, as I’d be interested in how to do this myself.
At the current time, this appears to not be possible. You can easily make it work if you want a
List<Bar>in the Foo object using the<collection>mapping.I tried using
<collection>to return a Map, but it doesn’t understand what I’m asking it to do.The only way I know to do this right now is to manage it yourself with two queries/mappings – one to populate Foo with all its fields other than its collection of Bars. Then a query mapping like the one listed below to pull back all Bars in a Map and plug that into your Foo object yourself:
This will return a Map with one entry for each bar, where the key to the entry is the value of the “bar_name” column.
The MyBatis team recommended putting in an issue request for this feature in a future release.