Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid automatic entity update on Hibernate ValidationException

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.

like image 737
Suganthan Madhavan Pillai Avatar asked Mar 11 '26 14:03

Suganthan Madhavan Pillai


1 Answers

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;
}
like image 186
Vlad Mihalcea Avatar answered Mar 14 '26 03:03

Vlad Mihalcea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!