3

I having a spring method: where I am validating the entity after constructing of object, which was previously fetched from DB.

@Transactional(rollbackFor={ValidationException.class})
    public Object approve(Command command) throws ValidationException {
        Object obj = merger.mergeWithExistingobject(command); // where I am fetching object from DB with old values and construct the new object

        validatorService.validate( obj ); // which throws ValidationException

        return saveObject(obj);
    }

But unfortunately even after the ValidationException was thrown. The values still get persisted in DB. How can I avoid this situtation.

8
  • Are you sure you aren't commiting changes in mergeWithExistingobject? Commented Jul 23, 2015 at 9:43
  • Is validatorService under spring control ? Post ValidatorService code please. Commented Jul 23, 2015 at 9:45
  • @Suganthan can you provide the exception log ? Commented Jul 23, 2015 at 9:47
  • @DraganBozanovic, yes I am sure.I am getting an object from DB and updating new changes that it. Commented Jul 23, 2015 at 9:52
  • @PawełGłowacz yes it is spring managed bean Commented Jul 23, 2015 at 9:53

2 Answers 2

1

You can evict the entity on ValidationException:

try {
    validatorService.validate( obj );
} catch (ValidationException e) {
    entityManager.detach(obj);
    //Or with Hibernate API
    //session.evict(obj); 
    throw e;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I've never used spring but if this is the same as EJB then transactions are only rolled back when unchecked exceptions are thrown.

When a java.lang.Exception is thrown from the EJB method, you obviously have to declare it in the method's signature with thethrows keyword. What happenes in this case as follows 1) the transaction gets commited 2) the exception is rethrown to the client

Taken from this link

1 Comment

Yes you are right. But In my case even if exception thrown. transaction will get commited because if isDirty check

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.