I'm trynig to do one lock with no succes,
i have one table named 'TbSelo' so i have a lot of records here, and i have one service that my user can reserve one record.
so i do one select to get one or more records unreserved an update that record with informations from this user. but when i have a few user asking for records ano or more receive the same record.
so i try to lock my register just like this:
Code:
boolean erro = false;
SeloReservado seloReservado = null;
do{
erro = false;
try{
session.getTransaction().begin();
Criteria criteria = session.createCriteria(TbSelo.class);
criteria.add(Restrictions.isNull("dtSolicitacao"));
criteria.add(Restrictions.isNull("dtUtilizacao"));
criteria.add(Restrictions.eq("icGratuito", icGratuito));
criteria.addOrder(Order.asc("cdSelo"));
criteria.setMaxResults(1);
TbSelo selo = null;
selo = (TbSelo) criteria.uniqueResult();
selo.setNmNaturezaSolicitacao(nmNatureza);
selo.setNmUsuarioSolicitacao(nmUsuario);
selo.setDtSolicitacao(new Timestamp(Calendar.getInstance().getTime().getTime()));
session.update(selo);
session.getTransaction().commit();
seloReservado = new SeloReservado(selo.getNmSerie(), String.format("%05d", selo.getNrSerie()), icGratuito, selo.getAleatorio());
}catch (StaleObjectStateException e ){
erro = true;
session.getTransaction().rollback();
}
}while(erro);
but when i test this code, some users returns correct and from some user i get a infinit loop.
i try to use @Version in my entity, and try to put criteria.setLockMode(LockMode.PESSIMISTIC_WRITE); in my criteria
when i debug the code, I noticed that when the loop back to init the criteria always return the same records regardless of it field are change( in this case that records have dtSolicitacao filled) i try to use session.evict(selo) but dont work
can someone help me? tks
I using Postgresql