I am trying to check if an entity being edited was changed by another source. I managed to detect changes in the @ManyToOne relationships and primitive fields, however the collections were not affected:
@OptimisticLocking(type = OptimisticLockingType.ALL_COLUMNS)
@Entity(name = "RNC_RELATORIO")
public class RncRelatorio implements Serializable{
@ManyToOne
@JoinColumn(name = "emitente_id")
private SosUsuario emitente;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "relatorio", orphanRemoval = true)
private List<RncAcao> acoes = new ArrayList<>();
...
I found some articles about using versioning by creating another field in the table that gets incremented after every update. Is there another way? If not, where should the version column be placed?
EDIT 1:
I added a version column in the RNC_RELATORIO table and mapped it in the RncRelatorio entity with the @Version annotation. Also changed the @OptimisticLocking type and the cascade value. Now everytime i am editing an object and i try to update it, i get an exception if the version from the database table is not equal to the one object's one. This happens even if nothing was changed in the entity during the update, but that's not a problem.
@OptimisticLocking(type = OptimisticLockingType.VERSION_COLUMN, cascade = true)
@Entity(name = "RNC_RELATORIO")
public class RncRelatorio implements Serializable{
@Version
private int version;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
...
EDIT 2
When i try to get the sysdate from Oracle database i get the optimistic locking exception after the database was changed somewhere else even though i am just running a select through the RncRelatorio DAO and not trying to update the table row. Any idea why?
public class GenericDAO<T> implements Dao<T> {
private final Class<T> clazz;
private final EntityManager em;
public GenericDAO(Class<T> _clazz) {
this.clazz = _clazz;
this.em = PersistenceFactory.getInstance();
}
@Override
public Date getSysdate() {
Query q = em.createNativeQuery("select sysdate from dual");
List<Timestamp> l = q.getResultList();
Date d = new Date(l.get(0).getTime());
return d;
}
}
public class RncRelatorioDao extends GenericDAO<RncRelatorio>{
public RncRelatorioDao() {
super(RncRelatorio.class);
}
}
The solution i found was adding a version column so, even if nothing was changed in the update, the version is still incremented by 1. This way I can check if something was changed.