你如何映射一个“地图”在冬眠使用注释? [英] How do you map a "Map" in hibernate using annotations?

查看:103
本文介绍了你如何映射一个“地图”在冬眠使用注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



使用注释如何将字符串中的字段映射到String的Map(Hashtable)到给定对象?这个对象被注解了,它的实例已经存储在hibernate数据库中。



我发现了用简单的键和值定义映射的语法:


$ b

 < class name =Footable =foo> 
...
<地图角色=年龄>
< key column =id/>
< index column =nametype =string/>
< element column =agetype =string/>
< / map>
< / class>

奇怪的是一个实体作为键和一个简单类型,就像这样:

 < class name =Footable =foo> 
...
<地图角色=年龄>
< key column =id/>
class =Person/>
< element column =agetype =string/>
< / map>
< / class>
< class name =Persontable =person>
...
type =string/>
< / class>

但是我不知道如何做到这一点,您可以简单地使用 JPA注释

code> @MapKey (请注意,JPA注释与Hibernate不同,Hibernate @MapKey 映射一个保存地图键的数据库列,while JPA的注解映射了要用作映射关键字的属性)。

pre $ @ javax.persistence.OneToMany(cascade = CascadeType。 ALL)
@ javax.persistence.MapKey(name =name)
private Map< String,Person> nameToPerson = new HashMap< String,Person>();


Using annotations how do you map a field in an entity which is a "Map" (Hashtable) of String to a given object? The object is annotated and instances of it are already stored in the hibernate databse.

I've found the syntax for definging a map with a simple key and value as such:

<class name="Foo" table="foo">
    ...
    <map role="ages">
         <key column="id"/>
         <index column="name" type="string"/>
         <element column="age" type="string"/>
     </map>
 </class>

And oddly with an entity as the key and a simple type as the value like so:

<class name="Foo" table="foo">
    ...
  <map role="ages">
    <key column="id"/>
    <index-many-to-many column="person_id" 
         class="Person"/>
    <element column="age" type="string"/>
  </map>
</class>
<class name="Person" table="person">
    ...
    <property name="name" column="name" 
         type="string"/>
</class>

But I don't see how to do this for a simple key to element mapping, and I don't see how to do this using annotations.

解决方案

You could simply use the JPA annotation @MapKey (note that the JPA annotation is different from the Hibernate one, the Hibernate @MapKey maps a database column holding the map key, while the JPA's annotation maps the property to be used as the map's key).

@javax.persistence.OneToMany(cascade = CascadeType.ALL)
@javax.persistence.MapKey(name = "name")
private Map<String, Person> nameToPerson = new HashMap<String, Person>();

这篇关于你如何映射一个“地图”在冬眠使用注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆