如何添加地图< String,Person>在实体类中? [英] How to add a Map<String, Person> in an entity class?

查看:212
本文介绍了如何添加地图< String,Person>在实体类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个映射作为

Map<String, Person> personMap;

在一个实体类中,其中 Person 实体。 Map 是要确定对应于 String Person (让它成为那个人的昵称)。同一个人可能会有不同的名字,只要有任何一个姓名,就必须找到相同的 Person

inside an entity class, where Person is the entity. The Map is to identify the exact Person corresponding to the String (let it be a nickname of that person). The same person may have different names and whenever any of the names is given, the same Person has to be found.

Persistance API使用的是JPA,提供程序是EclipseLink。我应该使用什么注释,如何?

Persistance API used is JPA and the provider is EclipseLink. What annotation should I use and how?

推荐答案

根据JSR-317的2.7节,如果Map的值为实体(这是你的情况),创建一个连接表,然后应该使用OneToMany / ManyToOne注释。

As per section 2.7 of JSR-317, if the value of the Map is an entity (which is your case) a join table is created and then a OneToMany / ManyToOne annotation should be used.

至于键,如果是基本类型, @MapKeyColumn可用于自定义键的映射列。所以这里是我的例子:

As for the key, if it is a Basic Type, the @MapKeyColumn can be used to customize the mapping column of the key. So here is my take on your example:

@OneToMany
@MapKeyColumn(name="person_nickname")
Map<String, Person> personMap;

EDITED:

经过一些测试,以下内容似乎很好:

After some testing, the following seems to work pretty well:

@ElementCollection
@CollectionTable(name="<name_of_join_table>")
@MapKeyColumn(name="<name_of_map_key_in_table>")
Map<String, Person> personMap;

以上生成一个具有三个字段的连接表:一个用于映射持有人id,一个用于键另一个为该值。

The above generates a join table with three fields: one for the mapping holder id, one for the key and one for the value.

这篇关于如何添加地图&lt; String,Person&gt;在实体类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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