Hibernate Optimistic Locking can be bypassed using hibernate Session (http://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/Session.html) replicate(...) method.
//Detaching to prevent hibernate to spot dirty fields. //Otherwise if entity exists in hibernate session replication will be skipped //and on flush entity will be updated with version increment. em.detach(entityDb); someTimeConsumingProcessingOfEntityFields(entityDb); //Telling hibernate to save without any version modifications. //Update hapends only if no newer version exists. //Executes additional query DB to get current version of entity. hibernateSession.replicate(entity, ReplicationMode.LATEST_VERSION); I think this solution is better than native SQL update, because:
- ORM mappings (anotations or *.hbm.xml) are uses (no need to duplicate Java objects <-> DB Tables mapping in native queries);
- no need to manually execute flush (performance);
- db and hibernate caches are in same state, no need to evict entities form cache (perfomance);
- and you still have all ORM provided features like optimistic locking, and so on... ;