2013-04-14 15 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