I’ve got a problem with the removal of entities in my JPA application: basically, I do in this EJB Business method:
load photo list ;
for each photo {
//UPDATE
remove TagPhoto element from @OneToMany relation
//DISPLAY
create query involving TagPhoto
...
}
and this last query always throws an EntityNotFoundException (deleted entity passed to persist: […TagPhoto#])
I think I understand the meaning of this exception, like a synchronization problem caused by my Remove, but how can I get rid of it?
EDIT: here is the stack of the exception:
Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [net.wazari.dao.entity.TagPhoto#<null>]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:621)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:74)
at net.wazari.dao.jpa.TagFacade.loadVisibleTags(TagFacade.java:108)
and the mapping between Tag-TagPhoto-Photo
public class Tag implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "tag")
private List<TagPhoto> tagPhotoList;
}
public class TagPhoto implements Serializable {
...
@JoinColumn(name = "Tag", referencedColumnName = "ID")
@ManyToOne(optional = false)
private Tag tag;
@JoinColumn(name = "Photo", referencedColumnName = "ID")
@ManyToOne(optional = false)
private Photo photo;
}
public class Photo implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL , mappedBy = "photo")
private List<TagPhoto> tagPhotoList;
}
(it was automatically generated by Netbeans when I created the project)
EDIT: Does it mean that tagPhoto != tagPhoto.getTag().getTagPhotoList().get(...) != tagPhoto.getPhoto().getTagPhotoList().get(...)?
and how shall I remove them? iterator.remove should not be of any use, and I would think that three em.remove() would do three times the same operation …
To be honest, it’s hard to say without the mappings (especially the cascading options), without the exact stack trace and without the real code as the pseudo code is very likely not showing the real problem. So this answer is more a shot in the dark (and you should consider posting the mentioned details).
My guess is that you’re calling
remove()on aTagPhotoinstance that you are not removing from the one-to-many association. So when theEntityManagertries to update the parent Photo, it may indeed try to persist a deleted entity, hence the exception.Update: You need to remove the
TagPhotoinstance from both collections that contain it:Note that things are actually a bit more complicated because NetBeans generated an Entity for the join table (TagPhoto). It would be a bit easier if you had a many-to-many association between
PhotoandTag. But in any case, when you remove an entity, you need to remove it from associations, JPA won’t do that for you.