merge - Spring-Data JPA: save new entity referencing existing one -
the question same below one:
jpa cascade persist , references detached entities throws persistentobjectexception. why?
i'm creating new entity references existing, detached one. when save entity in spring data repository exception thrown:
org.springframework.dao.invaliddataaccessapiusageexception: detached entity passed persist
if @ save() method in source code of spring data jpa see:
public <s extends t> s save(s entity) { if (entityinformation.isnew(entity)) { em.persist(entity); return entity; } else { return em.merge(entity); } }
and if @ isnew() in abstractentityinformation
public boolean isnew(t entity) { return getid(entity) == null; }
so if save() new entity (id == null)
, spring data call persist , hence scenario fail.
this seems typical use case when adding new items collections.
how can resolve this?
edit 1:
note:
this issue not directly related how save new entity refers existing entity in spring jpa?. elaborate assume request create new entity on http. extract information request , create entity , existing referenced one. hence detached.
i had similar issue trying save new entity object saved entity object inside.
what did implemented persistable< t > , implemented isnew() accordingly.
public class myentity implements persistable<long> { public boolean isnew() { return null == getid() && subentity.getid() == null; }
or use abstractpersistable , override isnew there ofcourse.
i don't know if considered way of handling issue worked out quite me , besides feels natural do.
Comments
Post a Comment