Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map a "Map" in hibernate using annotations?

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.

like image 904
Omar Kooheji Avatar asked Feb 24 '10 17:02

Omar Kooheji


People also ask

Which annotation is used for is a mapping?

The @Basic annotation is used to map a basic attribute type to a database column.

How do you map in hibernate?

Define Hibernate Mapping FileThe <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

Which annotation is used for mapping is a relationship in hibernate?

In order to map a Many-to-Many relationship we'll use the @ManyToMany annotation.

What is the use of @entity annotation in hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default.


2 Answers

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>(); 
like image 139
Pascal Thivent Avatar answered Sep 20 '22 17:09

Pascal Thivent


@CollectionOfElements(fetch = FetchType.LAZY) @JoinTable(name = "JOINTABLE_NAME",     joinColumns = @JoinColumn(name = "id")) @MapKey(columns = @Column(name = "name")) @Column(name = "age") private Map<String, String> ages = new HashMap<String, String>(); 
like image 28
whiskeysierra Avatar answered Sep 20 '22 17:09

whiskeysierra