我想用 MyBatis 将数据映射到 java.util.Map
属性。我有这样简单的 POJO:
public class Bar {
...fields
}
public class Foo {
private Map<String, Bar> bars;
public Foo() {
bars = new HashMap<String, Bar>();
}
...
}
如何使用 MyBatis 将数据映射到条形图?下面的示例不起作用,因为它始终将新 map 设置为字段。
<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>
最佳答案
我已经对此进行了一些研究,并在 MyBatis Google 小组上进行了询问,因为我对自己如何做这件事很感兴趣。
目前,这似乎是不可能的。如果你想要一个List<Bar>
,你可以很容易地让它工作。在 Foo 对象中使用 <collection>
映射。
我尝试使用 <collection>
返回 map ,但它不明白我要它做什么。
我现在知道的唯一方法是使用两个查询/映射自行管理它 - 一个是用它的所有字段填充 Foo, 它的 Bars 集合。然后像下面列出的查询映射来拉回 Map 中的所有 Bars 并自己将其插入到您的 Foo 对象中:
@Select("SELECT bar_id, bar_name FROM bar WHERE foo_id = #{id}")
@MapKey("bar_name")
Map<String, Bar> getBarsById(int id);
这将返回一个映射,其中每个柱都有一个条目,其中条目的键是“bar_name”列的值。
MyBatis 团队建议在未来的版本中针对此功能提出问题请求。
关于java - 使用 MyBatis 映射 java.util.Map 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11496161/