JPA insert parent/child results in MySQLIntegrityConstraintViolationException

前端 未结 4 1212
情歌与酒
情歌与酒 2020-12-29 00:12

This has already been asked a number of times, but I don\'t find any good answers so I\'ll ask it again.

I have parent-children unidirectional relation as follows:

4条回答
  •  無奈伤痛
    2020-12-29 00:58

    I know persisting a new parent with children works for me using em.persists(...).

    Using em.merge(...), really I don't know, but it sounds like it should work, but obviously you are running into troubles as your JPA implementation is trying to persists children before parent.

    Maybe check if this works for you : https://vnageswararao.wordpress.com/2011/10/06/persist-entities-with-parent-child-relationship-using-jpa/

    I don't know if this plays a role in your problem, but keep in mind that em.merge(p); will return a managed entity... and p will remain un-managed, and your children are linked to p.

    A) try em.persists(...) rather than em.merge(...)

    if you can't

    B) you are merging parent... and you cascade is set to CascadeType.PERSIST. Try changing it to

    • cascade=CascadeType.ALL
      or
    • cascade={CascadeType.PERSIST, CascadeType.MERGE}

    I know merge will persists newly created entities and should behave as persists, but these are my best hints.

提交回复
热议问题