0
votes

I'm new to JPA Hibernate implementation and I'm trying to understand how EntityManager.merge works.
I have the following scenario of two classes with @ManyToOne relation e.g

class A{
   private String name;
   ........
   get...
   set...
}

class B{
   private String name;

   @ManyToOne(fetch=FetchType.LAZY, cascade=CascadeType.MERGE)
   private A a;
   ........
   get...
   set...
}

And I have GUI where you can view and change only B property's - the A class is not loaded and there is no Open Session in View.
When trying to save(merge) changes in back-end:

entityManager.merge(b); //the object "b" created from view has "a" set to null

In database in table B the foreign key relationship(referencing to table A) is lost - set to null;
This is not what a want I want to keep the relationship and merge-save the changes made in the GUI to object B with out losing the Many-To-One relationship
Maybe what I'm expecting is not possible and what I need to do is:

 dbB b = entityManager.find(B.class, id);
 dbB.setName(b.getName());
 dbB.set........
 entityManager.merge(dbB);
1

1 Answers

1
votes

If in entityManager.merge(b); the relation b.a is null, merge will delete the foreign key. That's because the value null doesn't mean the reference should be ignored but that the reference should be removed (i.e. there is no reference anymore).

I want to keep the relationship and merge-save the changes made in the GUI to object B with out losing the Many-To-One relationship

One option would be to read the entity from the database with a being initialized to a lazy proxy and pass it to the gui. During that process the entity will most likely get detached and hence you need to merge it during save. However, since a won't be null in that case, the reference should not get lost.