문제

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