JPA How can I get the generated id/object when using merge from parent but child is created?

前端 未结 4 1543
孤独总比滥情好
孤独总比滥情好 2021-01-04 20:47

I have an entity that has been previously persited and has a @OneToMany relationship with another entity. In order to add a new entity I just add my new entity

4条回答
  •  心在旅途
    2021-01-04 20:52

    Make sure that you are setting both sites of the relationship before persisting the changes.

    child.setParent(parent);
    parent.getChildren().add(child);
    Parent parentWithId = em.merge(parent);
    em.flush(); // make sure that the persistence context and database are in sync
    parentWithId.getId(); // works
    parentWithId.getChildren().get(0).getId(); // should also work
    

提交回复
热议问题