gpt4 book ai didi

java - JPA2 唯一约束 : do I really need to flush?

转载 作者:搜寻专家 更新时间:2023-11-01 03:29:40 25 4
gpt4 key购买 nike

我有一个 DAO,我需要在其中捕获唯一约束异常。为此,唯一可行的解​​决方案是在持久化后刷新我的 EntityManager。直到那时我才进入一个 catch block ,我必须在其中过滤掉异常。而且,我的 DAO 方法需要包装在事务 (REQUIRES_NEW) 中,否则我会遇到 RollBackException。

我做错了什么吗?

try {
em.persist(myObject);
em.flush();
} catch (PersistenceException ex) {
if (ex.getCause() != null) {
String cause = ex.getCause().toString();
if (cause != null) {
if (cause.contains("org.hibernate.exception.ConstraintViolationException")) {
logger
.error("org.hibernate.exception.ConstraintViolationException: possible unique constraint failure on name");
throw ex;
}
}
}
}

最佳答案

Am I doing something wrong?

EntityManager#persist() 不会触发立即插入(除非您使用的是 IDENTITY 策略)。因此,如果您想将内存中的更改实际写入数据库并有机会捕获约束违规,您必须“手动”flush()(尽管即使这样做也不能严格保证任何东西,您的数据库都可以配置为使用延迟约束)。

换句话说,在我看来,您的做法是正确的。


I have a service method with a @Transactional on it (REQUIRED) called addNewObject(). In this method some stuff happens that might throw an exception (and thus rollback the transaction). One of these calls is a call to the DAO method addObject. This one might fail because of the unique constraint. Now, if I do flush, the object will be persisted if there is no unique violation. However, within the service there might still be something else that causes the method to throw an exception.

我认为您混淆了 flushcommit。如果在 addObject 之外出现问题并抛出不可恢复的异常(但在同一个事务内),整个事务将被回滚,包括与 对应的 INSERT 语句>persist() 调用。综上所述,flush != commit

关于java - JPA2 唯一约束 : do I really need to flush?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3967540/

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