How to use an object with a composite key as map collection key Hibernate

Viewed 80

We have class that contains a map collection as follows:

@ElementCollection
private final Map<Item, Integer> items;

Item is a class with a composite primary key:

@IdClass(ItemId.class)
public class Item {
    @Id
    private int id;
    @Id
    private int storeId;

ItemId is an id class as recommended for such cases:

package store;

import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;

@Embeddable
public class ItemId implements Serializable {
    private int id;
    private int storeId;

    public ItemId() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getStoreId() {
        return storeId;
    }

    public void setStoreId(int storeId) {
        this.storeId = storeId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ItemId itemId = (ItemId) o;
        return id == itemId.id && storeId == itemId.storeId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, storeId);
    }
}

This causes the following runtime error:

Caused by: org.hibernate.AnnotationException: A Foreign key refering store.Item from store.Inventory has the wrong number of column. should be 2

The recommended solution of using @MapKeyJoinColumn(name = "id") applies only when the map key refers to a single field and still gives the same error.

How do we get the map key to refer to both the primary key fields?

0 Answers
Related