Languages
[Edit]
EN

Hibernate - OneToMany join with Map by key from another column

5 points
Created by:
Violet-Hoffman
652

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...
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join