Question

I've the code:

modifiedParentEntity.addChild(newChildEntity);
session.merge(modifiedParentEntity);
newChildEntity.getId(); // == 0!!! 

Where parent entity has a collection of child entities with CascadeType.ALL:

@Entity
public class ParentEntity {
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    @JoinColumn(name = "parent_entity_id")
    private List<ChildEntity> childEntities;
}

Question:

  1. Why after session.merge(modifiedParentEntity) chidEntity has 0 id?
  2. How to save both modifiedParentEntity and chidEntity in a way that Hibernate will set id to chidEntity?

P.S.:

I use postgres and sequences to generate entities' ids.

Was it helpful?

Solution

merge operation does not make the passed entity managed, but rather returns another instance that is managed

so you need to get the id from managed instance as follows

modifiedParentEntity.addChild(newChildEntity);
ModifiedParentEntity modifiedParentManaged= session.merge(modifiedParentEntity);
session.flush()

Then get the child entity from modifiedParentManaged and then get its id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top