事务服务中的 ConstraintViolationException 没有回滚

问题描述:

我有一个名为 add() 的服务方法,它用 @Transactional 注释.

I've a service method called add() which is annotated with @Transactional.

我调用它,但是当在相应的 DAO 方法中发生 ConstraintViolationException 时,即使我指定不这样做,它也会回滚事务.

I call it but when a ConstraintViolationException occurs inside corresponding DAO method it'll rollback the transaction even when I specify not to.

我希望 ConstraintViolationException 被捕获,而不是 NotFoundException 被检查的异常会被抛出.

I expect that ConstraintViolationException to be caught and instead of it NotFoundException checked exception would be thrown.

@Override
@Transactional(noRollbackFor = ConstraintViolationException.class)
public User add(User user) throws NotFoundException {
    try {
        result = userDao.add(user);
    } catch (RuntimeException e) {
        throw new NotFoundException("Couldn't find group");
    }
}

有没有办法在没有事务回滚的情况下捕获ConstraintViolationException?

Is there a way to catch ConstraintViolationException without transaction rollback?

我使用的是 spring 3.1.1 和 hibernate 3.6.

I'm using spring 3.1.1 and hibernate 3.6.

啊,我明白了.ConstraintViolationException 在提交时发生,在方法执行之后,当围绕您的 add() 方法的事务拦截器尝试提交事务时.由于它无法提交,显然,事务被回滚.它不能用于其他任何东西.

Ah, I see what happens. The ConstraintViolationException happens at commit time, after the method has been executed, when the transaction interceptor around your add() method tries to commit the transaction. Since it can't commit, obviously, the transaction is rollbacked. It can't to anything else.