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:
xxxxxxxxxx
1
package logic.database.entity;
2
3
import org.hibernate.annotations.Fetch;
4
import org.hibernate.annotations.FetchMode;
5
6
import javax.persistence.*;
7
import java.util.Date;
8
import java.util.Map;
9
10
name = "groups") (
11
public class GroupEntity
12
{
13
14
15
private Long id;
16
17
private String name;
18
19
value = FetchMode.SELECT) (
20
fetch = FetchType.LAZY) (
21
name = "groupId", insertable = false, updatable = false) // groupId property is located in ItemEntity (
22
name = "type") // type property is located in ItemEntity (
23
private Map<String, ItemEntity> items; // should keep all items accessed by type property from ItemEntity
24
// type property from ItemEntity has String type so map key is String type too
25
26
// getters and setters here...
27
}
ItemEntity.java
file:
xxxxxxxxxx
1
package logic.database.entity;
2
3
import org.hibernate.annotations.Fetch;
4
import org.hibernate.annotations.FetchMode;
5
6
import javax.persistence.*;
7
import java.util.Date;
8
import java.util.List;
9
10
name = "items") (
11
public class ItemEntity
12
{
13
14
15
private Long id;
16
17
private String name;
18
private String description;
19
private String type; // in our case it is unique key in database with groupId property
20
// so in MySQL it should be: UNIQUE KEY (`group_id`, `type`)
21
22
private Long groupId; // groupId and group properties describe same relation
23
24
value = FetchMode.JOIN) (
25
fetch = FetchType.EAGER) (
26
name = "id", insertable = false, updatable = false) // id property is located in GroupEntity (
27
private GroupEntity group; // groupId and group properties describe same relation
28
29
// getters and setters here...
30
}