gpt4 book ai didi

java - 使用实体管理器删除有时会失败

转载 作者:行者123 更新时间:2023-12-01 14:40:32 24 4
gpt4 key购买 nike

我在从数据库中删除持久对象时遇到问题。我有一些表之间具有双向关系。我有一个测试,用于删除仍被其他对象引用的对象,但有时会失败。我不明白为什么会这样。

我的人际关系是这样的:

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

异常(exception):

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

最佳答案

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

像这样:

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

也许一些缓存在后台工作,有时我在对象中具有正确的关联,有时则没有,但我不确定。

关于java - 使用实体管理器删除有时会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com