Hibernate 3 and 4 could not handle the deletion of entities shows below
Code:
class Master { @OneToMany List<Apprentice> apps; }
class Apprentice { @ManyToOne Master master; }
class Skill { /* an ordinary entity class */ }
class Proficiency {
ProficiencyPK id;
@ManyToOne Skill s; @ManyToOne Apprentice a; }
class ProficiencyPK { Integer skillId; Integer Apprentice appId; }
I inserted sample data for testing:
Master has 3 apprentice,
Skills Table have 3 skills(as constant) prepared for testing;
Thus, an apprentice has 3 proficiency entities associated with each skill.
The insertion is good. But when I test the deletion, it fails.
Code:
Master m = getOneSampleFromEntityManager();
List<Apprentice> lsta = m.getApprentices();
for(Apprentice a: lsta) {
List<Proficiency> lstp = getFromEntityManagerByApprentice(a);
for(Proficiency p: lstp) {
em.remove(p); //!! Exception, see below
}
}
The exception is
Code:
Exception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:93)
at test.jpa.run.TestIndirectDep.test(TestIndirectDep.java:79)
at test.jpa.run.TestIndirectDep.main(TestIndirectDep.java:88)
Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [test.jpa.entity.indirectdep.Apprentice#<null>]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1197)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1148)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:81)
... 2 more
Please note the apprentice is not deleted yet(the proficiency has dependency of it, so I have to delete the proficiency first. If I delete apprentice first, the database will throw a constraint violation). I do not have any cascade annotation.
Because remove the entity one by one failed, I tried to do batch update like
Code:
delete from Proficiency e where e.app=:app
It still fails with the same exception. I tested the code with Hibrenate 3.6.7(the exception shown above is with 3.6.7) and 4.0.0. The hibernate acts exactly the same.
However, I switched to EclipseLink, it works as expected(deletion is successful). So I wonder if there is a special way to do it with Hibernate. Maybe it could be entity manager bugs?
If there is a way to upload the source code I would do that.