سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top