Hibernate's optimistic locking and DTOs

Sep 26, 2010   #hibernate  #java 

Hibernate can do optimistic locking and detect version conflicts by using a version column.

However, if you are using DTOs and you expect Hibernate to detect version conflicts based on the version you are merging back from the DTO into your entity object, this will not work.

Hibernate will ignore the version you are setting in your DTO2Entity mapper and overwrite any changes that may have been made to the entity before your DTO arrives back at the application core. You have to do version checking by your own.

entity = entityDAO.findById(dto.getId());
if (entity.getVersion() > dto.getVersion()) {
    throw new Exception("Optimistic Lock Exception");
else {
    // Map and merge entity...