This blog is mainly about Java...

Tuesday, September 2, 2008

Deleted entity passed to persist exception

Deleting an entity was seemingly more difficult than I thought.
I thought that I could just loop through a list, find the objects I wanted to delete and just delete them.

Look at this block of code:

List relasjoner = entityManager.createQuery(
"SELECT rel FROM " + Relasjon.class.getName() + " rel " + "WHERE rel.personA.personId = " + personb.getPersonId()
+ " OR rel.personB.personId = " + personb.getPersonId()).getResultList();

for (Relasjon rel : relasjoner) {
if((rel.getPersonB().getPersonId().equals(personb.getPersonId()) || rel.getPersonA().getPersonId().equals(personb.getPersonId()))
// Time to remove
log.debug("Going to remove this relasjon with id: " + rel.getRelasjonId());

The line entityManager.remove(rel) gave me a "Deleted entity passed to persist" exception with Relasjon<#null>
After some Googling I found out that I had to add these two lines before trying to remove the entity:


getRelasjonsForPersonA() is a Set of persons.
So I have to remove all the references to a Relasjon first before deleting the entity, and then no more exception.

1 comment:

Anonymous said...

before to call entityManager.remove(rel);

Your object rel must be attached with call the method:
entityManager.find(Relasjon.class, reg.getId());