EN
Hibernate - OneToMany join with Map by key from another column
5
points
In this short article we would like to show you how in Hibernate use @OneToMany
annotation with Map<?, ?>
property type to make join with indicated colum as map key.
e.g. Map<String, ?>
, Map<Integer, ?>
, Map<Long, ?>
, etc.
Note: the example was tested on different database, if something doesn't work contact with us (go to about page).
Quick solution (for String
key type):
GroupEntity.java
file:
package logic.database.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.Date;
import java.util.Map;
@Table(name = "groups")
public class GroupEntity
{
@Id
@GeneratedValue
private Long id;
private String name;
@Fetch(value = FetchMode.SELECT)
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "groupId", insertable = false, updatable = false) // groupId property is located in ItemEntity
@MapKey(name = "type") // type property is located in ItemEntity
private Map<String, ItemEntity> items; // should keep all items accessed by type property from ItemEntity
// type property from ItemEntity has String type so map key is String type too
// getters and setters here...
}
ItemEntity.java
file:
package logic.database.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Table(name = "items")
public class ItemEntity
{
@Id
@GeneratedValue
private Long id;
private String name;
private String description;
private String type; // in our case it is unique key in database with groupId property
// so in MySQL it should be: UNIQUE KEY (`group_id`, `type`)
private Long groupId; // groupId and group properties describe same relation
@Fetch(value = FetchMode.JOIN)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id", insertable = false, updatable = false) // id property is located in GroupEntity
private GroupEntity group; // groupId and group properties describe same relation
// getters and setters here...
}