我从数据库中删除持久对象时遇到问题。我有一些表之间存在双向关系。我有一个删除仍然被另一个对象引用的对象的测试,这有时会失败。我无法弄清楚为什么会这样。
我的人际关系是这样的:
@ManyToOne(cascade = CascadeType.ALL, targetEntity = Application.class, optional = false)
@JoinColumn(name = ModelConstants.ID_APPLICATION, nullable = false, insertable = true, updatable = true)
private Application application;
@OneToMany(cascade = CascadeType.ALL, targetEntity = Clazz.class, mappedBy = "pakage")
private List<Clazz> clazzes;
你有什么想法,为什么我不能通过 EntityManager 删除一行?
我的测试:
@Test
public void testDeleteMethodReferencedByMethodCall() {
Application application = new Application("", "testApplication");
Pakage pakage = new Pakage("", "testPakage", application);
Clazz clazz = new Clazz("", "testClazz", pakage);
Method methodCaller = new Method("testFirstMethod", "testMethodFirst",
clazz);
Method methodCalled = new Method("testSecondMethod", "testMethodSecond",
clazz);
MethodCall methodCall = new MethodCall(methodCaller, methodCalled);
DatabaseUtils.persistObject(entityManager, methodCall);
assertEquals(2, getCountRows("m", entityMethod));
assertEquals(1, getCountRows("mc", entityMethodCall));
DatabaseUtils.removeObject(entityManager, methodCall);
assertEquals(0, getCountRows("m", entityMethod));
assertEquals(0, getCountRows("mc", entityMethodCall));
}
移除对象:
public static void removeObject(EntityManager entityManager,
DatabaseElement databaseElement) {
entityManager.getTransaction().begin();
entityManager.remove(databaseElement);
entityManager.getTransaction().commit();
}
例外:
javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: update or delete on table "pakage" violates foreign key constraint "fk_clazz_id_pakage" on table "clazz"
Detail: Key (id_pakage)=() is still referenced from table "clazz".
Error Code: 0
Call: DELETE FROM public.pakage WHERE (id_pakage = ?)
bind => [1 parameter bound]
Query: DeleteObjectQuery(Pakage[id_pakage = , name_pakage = testPakage, Application[id_application = , name_application = testApplication]]) at