我尝试使用我已添加到实体对象中的JPA @Version
注释来测试乐观锁定:
@Version
@Setter(AccessLevel.NONE)
@Column(name = "VERSION")
private long version;
当我同时运行2台服务器时,我收到StaleObjectStateException
:
Exception message is : Object of class [com.myPackage.WorkQueue] with identifier [9074]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.myPackage.WorkQueue#9074]
我期待看到1)OptimisticLockException
发生,2)@transaction
因此回滚。
用例如下:条目被插入到Oracle数据库表中,状态为' NEW'。一旦线程检索到状态=' NEW'的行,它就会将表中行的状态更新为' IN_PROGRESS'。如果另一个事务已成功更新该行,我需要确保同时读取同一行的任何事务失败/回滚。
服务:
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor=Exception.class, readOnly=false)
public WorkQueue retrieveWorkQueueItemByStatus(WorkQueueStatusEnum workQueueStatus) {
return workQueueRepository.retrieveWorkQueueItemByStatus(workQueueStatus);
}
实施:
@Override
public WorkQueue retrieveWorkQueueItemByStatus(WorkQueueStatusEnum workQueueStatus) {
log.debug("Start - Attempting to select a " + workQueueStatus + " workQueue item in retrieveWorkQueueItemByStatus()");
try {
String sql = "SELECT a FROM WorkQueue a WHERE workQueueStatus = :workQueueStatus ORDER BY idWorkQueue ASC";
TypedQuery<WorkQueue> query = em.createQuery(sql, WorkQueue.class).setParameter("workQueueStatus", workQueueStatus)
.setFirstResult(0).setMaxResults(1);
WorkQueue workQueue = (WorkQueue) query.getSingleResult();
if (workQueue != null) {
workQueue.setWorkQueueStatus(WorkQueueStatusEnum.IN_PROGRESS);
WorkQueue updatedWorkQueue = em.merge(workQueue);
log.debug("Finish - selected the following workQueue item "+ workQueue.getIdWorkQueue() + " with the Audit Event Key from retrieveWorkQueueItemByStatus() : " + updatedWorkQueue.getAuditEventKey());
return updatedWorkQueue;
}
} catch (IllegalArgumentException iae) {
log.error("An IllegalArgumentException occured in workQueueRepositoryImpl.retrieveWorkQueueItemByStatus() attempting to execute query : " + sql + ". Exception message is : " + iae.getMessage());
} catch(Exception ex) {
log.error("An Exception occured in workQueueRepositoryImpl.retrieveWorkQueueItemByStatus() executing query : " + sql + ". Exception message is : " + ex.getMessage());
}
log.debug("Finish - returning null from retrieveWorkQueueItemByStatus()");
return null;
}
答案 0 :(得分:0)
有关异常类型,请参阅this question。
事务不会自动回滚。永远不应该使用Hibernate会话捕获并继续这种异常。原因是会话可能已部分同步到数据库,因此数据库状态可能不一致。因此,请将异常抛出事务之外,然后回滚,并重新开始新会话。