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

前端 未结 4 1567
孤独总比滥情好
孤独总比滥情好 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 21:00

    Stackoverflow post and JPA documentation have the answer provided that you do your research.

    The way to do what I want is to use persist on the managed parent. This will ignore any changes on the parent, but will cascade persist (provided that it is set up to cascade). The child object will have the correct id afterwards.

    ....
    JPAEntity newObject=new JPAEntity();
    managedObject.addChild(newObject);
    em.persist(managedObject)
    newObject.getId() //work fine!
    

提交回复
热议问题