Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a Map<String, Person> in an entity class?

I want to add a mapping as

Map<String, Person> personMap;

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 used is JPA and the provider is EclipseLink. What annotation should I use and how?

like image 535
Naveed S Avatar asked Sep 23 '11 06:09

Naveed S


1 Answers

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.

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;

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

like image 92
Gonzalo Garcia Lasurtegui Avatar answered Sep 30 '22 17:09

Gonzalo Garcia Lasurtegui