使用entitymanager删除有时会失败

时间:2013-04-14 19:58:33

标签: java database postgresql eclipselink persistent

我从数据库中删除持久化对象时遇到问题。我有一些表与它们之间存在双向关系。我已经测试了删除仍然被其他对象引用的对象,这有时会失败。我无法弄清楚为什么会这样。

我的关系看起来像这样:

@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));
}

REMOVEOBJECT:

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 

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:如果我在删除之前调用对象的刷新,那么一切正常。

像这样:

entityManager.refresh(databaseElement);
entityManager.remove(databaseElement);

也许有些缓存可以在后台运行,有时我在对象中有正确的关联,有时不是,但我不确定。