No rollback for ConstraintViolationException in tr

2019-02-15 11:05发布

问题:

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

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

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");
    }
}

Is there a way to catch ConstraintViolationException without transaction rollback?

I'm using spring 3.1.1 and hibernate 3.6.

回答1:

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.