Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable auto update in hibernate/JPA

Is it possible to stop hibernate from auto updating a persistent object?

    @Transactional
    public ResultTO updateRecord(RequestTO requestTO) {

        Entity entity = dao.getEntityById(requestTO.getId());

         // now update the entity based on the data in the requestTO

         ValidationResult validationResult = runValidation(entity);

         if(validationResult.hasErrors()) {
            // return ResultTO with validation errors
         } else {
             dao.persist(entity);
        }
    }

Here is what happens in the code, I retrieve the entity which would be considered by hibernate to be in persistent state, then I update some of the fields in the entity, then pass the entity to validation. if validation fails, then don't udpate, if validation succeeds then persist the entity.

Here is the main issue with this flow: because I updated the entity for it to be used in the validation, it does not matter whether I call persist() method (on the DAO) or not, the record will always be updated because hibernate detects that the entity has been changed and flags it for update.

Keep im mind I can change the way i do validation and work around the issue, so I'm not interested in workarounds. I'm interested in knowing how i would be able to disable the hibernate feature where it automatically updates persistent objects.

Please keep in mind I'm using hibernates' implementation of JPA. so Hibernate specific answers dealing with hibernate specific API will not work for me.

I tried to look for hibernate configuration and see if I can set any configuration to stop this behavior but no luck.

Thanks

--EDIT --- I couldn't find a solution to this, so I opted to rolling back the transaction without throwing any RuntimeException even though I'm in a declarative transaction using:

TransactionInterceptor.currentTransactionStatus().setRollbackOnly();

which works like a charm.

like image 357
lutfijd Avatar asked Aug 31 '12 22:08

lutfijd


1 Answers

You can call the following code:

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
like image 140
Bartun Avatar answered Sep 18 '22 10:09

Bartun