Java – how to disable automatic updates in Hibernate / JPA
Can I stop hibernate from automatically updating persistent objects?
@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); } }
This is what happens in the code. I retrieve the entity that hibernate will be considered to be in a persistent state, then I update some fields in the entity, and then pass the entity to validation If the validation fails, do not udpate. If the validation succeeds, persist the entity
This is the main problem of this process: because I updated the entities that I want to use in validation, whether I call the persist () method in DAO is not important, because hibernate will always update the record to detect that the entity has been changed and marked as an update.
It reminds me that I can change the way I do verification and solve problems, so I'm not interested in solutions I'm interested to know how I can disable hibernate to automatically update persistent objects
Remember, I'm using hibernate's JPA implementation Therefore, the specific answer to hibernate's handling of Hibernate's specific API is invalid to me
I tried to find hibernate configuration to see if I could set any configuration to prevent this behavior, but I didn't have luck
thank you
– Edit - I can't find a solution, so I choose to roll back the transaction without throwing any runtimeException, even if I use it in a declarative transaction:
TransactionInterceptor. Currenttransactionstatus() uses setrollbackonly();
It acts like a charm
Solution
Configure flushmode for your session
http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/FlushMode.html