Detached entity passed to persist
jactor Sep 19, 2006 10:12 AMHi!
I receive an error when I try to persist an entity bean. I have a bean (A) which relates to another bean (B). This relation is annotated as @ManyToOne(cascade = CascadeType.ALL) and
@JoinColumn(nullable = false)
The enity bean (B) has only one property beside the autogenerated id (Long) which its name (b.getName()). This property is annotated with @Column(nullable = false, unique = true).
I use annotations over the fields of the properties.
When I persist/merge these entities I get
javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: a.package.B
The methods which tries to persist the entities are:
public Long saveOrUpdate(A a) { B b = a.getB(); b.setId(saveOrUpdate(b)); entityManager.flush(); // If b is persisted before, the persisting gives an exception // I have actually never tried the merge option as a.getId() is null... if (a.getId() != null) { entityManager.merge(a); return a.getId(); } entityManager.persist(a); return a.getId(); } public Long saveOrUpdate(B b) { B persistedB = get(b.getName()); if (persistedB != null) { return persistedB.getId(); } entityManager.persist(b); return b.getId(); }
Since B only have one property (name) and this is unique, my saveOrUpdate method of B only return the id of an allready saved instance. Therefore I use this id on B.setId(Long id) when the method is called.
If B has not been persisted before it works as intended, but if the instance of B is located in the database, then the exception is thrown when I try to persist A... When A is persisted (even though there is a merge option in the code, every time I use this code, I persist a new instance of A - a.getId() == null - which may have an allready persisted instance of B) this exception is thrown even if the correct id is located in the instance of B which is tried to be persisted with A.
Please help me with this exception. I thought a detached entity did not have a valid primary key (b.getId()), but this is not the case in this situation. I am growing frustrated...