简体   繁体   English

使用MyBatis映射java.util.Map字段

[英]Map java.util.Map field with MyBatis

I would like to map data to java.util.Map attribute with MyBatis. 我想使用MyBatis将数据映射到java.util.Map属性。 I have simple POJOs like this: 我有像这样的简单POJO:

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? 如何使用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. 我已经对此进行了一些研究,并向MyBatis Google小组进行了询问,因为我对自己如何进行感兴趣。

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. 如果要使用<collection>映射在Foo对象中使用List<Bar> ,则可以轻松使其工作。

I tried using <collection> to return a Map, but it doesn't understand what I'm asking it to do. 我尝试使用<collection>返回一个Map,但是它不理解我要它执行的操作。

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. 我现在知道的唯一方法是用两个查询/映射自己管理它-一个用Foo的所有字段( 除了 Bar的集合)填充Foo。 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: 然后是一个查询映射(如下所示),以拉回Map中的所有Bar,然后将其自己插入Foo对象:

@Select("SELECT bar_id, bar_name FROM bar WHERE foo_id = #{id}")
@MapKey("bar_name")
Map<String, Bar> getBarsById(int id);

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. 这将返回一个地图,其中每个条都有一个条目,其中条目的键是“ bar_name”列的值。

The MyBatis team recommended putting in an issue request for this feature in a future release. MyBatis团队建议在将来的版本中提出对此功能的发布请求。

About MyBatis and HashMap , that is effectively what it is. 关于MyBatis和HashMap,实际上就是它。

HashMap class implements Map . HashMap类实现Map。 Map is an inteface 地图是一个界面

therefore because HashMap implements Map , HashMap IS a Map. 因此, 因为HashMap实现Map,所以HashMap是Map。

Whether you use generics key,value on the end of it or not also. 是否使用泛型键,也要在其末尾使用值。

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM