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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With