2013-04-14 17 views
0

我有一个从我的数据库中删除持久对象的问题。我有一些表之间有双向关系。我有一个测试用于删除仍然被其他对象引用的对象,这有时会失败。我无法弄清楚为什么。删除与entitymanager有时失败

我的关系是这样的:你有什么想法

@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 
+0

你可以发布异常和你的测试实现吗? –

回答

1

我找到了解决办法:如果我把一个刷新的对象之前删除,然后一切正常精细。

像这样:

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

也许有些缓存工作在回地面,有时我不得不在对象正确的关联,有时不是,但我不知道。

+0

您必须保持双向关系的双方才能与数据库保持缓存异步。 – Chris