我对JPA很新,如果表达不清楚请原谅。
Basically I want to prevent concurrent modifications by using Optimistic Locking. I ve added the @Version attribute to my entity class.
I need to know if this algorithm on handling OptimisticLockException is sound. I m going to use the Execute Around Idiom like so:
interface UpdateUnitOfWork
{
doUpdate( User user ); /* may throw javax.persistence.PersistenceException */
}
public boolean exec( EntityManager em, String userid, UpdateUnitOfWork work)
{
User u = em.find( User, userid );
if( u == null )
return;
try
{
work.doUpdate( u );
return true;
}
catch( OptimisticLockException ole )
{
return false;
}
}
public static void main(..) throws Exception
{
EntityManagerFactory emf = ...;
EntityManager em = null;
try
{
em = emf.createEntityManager();
UpdateUnitOfWork uow = new UpdateUnitOfWork() {
public doUpdate( User user )
{
user.setAge( 34 );
}
};
boolean success = exec( em, "petit", uow );
if( success )
return;
// retry 2nd time
success = exec( em, "petit", uow );
if( success )
return;
// retry 3rd time
success = exec( em, "petit", uow );
if( success )
return;
}
finally
{
em.close();
}
}
我有一个问题,你如何决定何时停止重试?