0

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

1 Answer 1

0
@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

2
  • So this means my otherEntity Objects need a new variable field which stores their hascode? Sorry if this is a dump question. I am a beginner..
    – user4594524
    Feb 22, 2015 at 20:29
  • Yes. So you have to remember to update it whenerever you change the values of fields of entity object. I dont know why you chose keys to be hascodes (unless you ment DB hashcodes but then java will not know about them). To make sure that hashValue is always updated you may call a recalculation method before each JPA update/persist en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Events
    – Zielu
    Feb 22, 2015 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.