Search code examples
javahibernatejakarta-eejpaeclipselink

JPA: persist a Map including the original "key" value


I need to store a complex tree-like object structure using JPA.

There is a "top-level" class A on which I therefore can perform a CASCADE.ALL but I have a problem with a sub-object of Class B and a HashMap field.

The "key" of the Map is a hashcode of the object itself which is stored as a "value".

When I cascade persist an object B however the "key" column in database is always "null" (why?) even though the object has some key-values pairs.

I tried out some things like @MapKey, but when I later load the object from database, the key value is no longer the hashcode but an auto-generated id (not useful for me).

I have also tried @ElementCollection for the map, but then I get an synchronization error (I think this is because I trigger the whole persist only from the top-level class and some objectd point to each other).

@Entity
public class B
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToMany(cascade = CascadeType.ALL)
    //Tried @MapKey or @ElementCollection
    public Map<Integer, OtherEntity> otherEntities;

Thanks for any help, Alex


Solution

  • @MapKey(name="hashField")
    

    The hash value must be stored explicit in the OtherEntity.hashField. The mapkey is used to tell which of the other object properties is used as the key value