gpt4 book ai didi

java - JPA:合并并持久化,捕获 ConstraintViolationException

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:14 30 4
gpt4 key购买 nike

您好,我对如何在合并期间捕获 ConstraintViolationException 有疑问。我有我的 JPALogic 类,我想捕获异常以写下更多信息,这段代码完美运行,抛出 GenericSaveException:

try {
em.persist(o);
} catch (ConstraintViolationException e) {
System.out.println("*** CONSTRAINT VIOLATIONS");
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
System.err.println("*** VIOLATION: " + violation.getRootBeanClass().getSimpleName() + "::" + violation.getPropertyPath().toString() + " " + violation.getMessage());
}
throw new GenericSaveException();
}

但这不会抛出异常,导致javax.ejb.EJBException:事务中止,原因:javax.transaction.RollbackException:事务标记为回滚,原因:javax.validation.ConstraintViolationException:

try {
managed = (T) em.merge(o);
} catch (ConstraintViolationException e) {
System.out.println("*** JPALogic::merge --> CONSTRAINT VIOLATIONS");
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
System.err.println("*** VIOLATION: " + violation.getRootBeanClass().getSimpleName() + "::" + violation.getPropertyPath().toString() + " " + violation.getMessage());
}
throw new GenericSaveException();
}

为什么合并不抛出 ConstraintViolationException?我该怎么做才能捕获异常?

谢谢。

最佳答案

可能为时已晚,但我也遇到了同样的问题。

实际上这是 Hibernate 实现的某种方式,参见:https://issues.jboss.org/browse/AS7-4576 , 和 https://hibernate.atlassian.net/browse/HHH-7288说它不会修复。可能是此功能(首次调用时验证)适用于 EclipseLink,但我还没有尝试过。

为了解决这个问题,我在调用合并或持久化之前在我的服务层中使用了一些更改的逻辑,我运行以下命令:

Set<ConstraintViolation<Contact>> validations = validator.validate(data);
if (validations.size() > 0) {
Map<String, String> messages = new HashMap<>();
for (ConstraintViolation v : validations) {
messages.put(v.getPropertyPath().toString(), v.getMessage());
}

return Response.status(Response.Status.BAD_REQUEST).entity(messages).build();
}

validator 在我的 bean 中是简单的注入(inject):

@Inject
Validator validator;

关于java - JPA:合并并持久化,捕获 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538713/

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