簡體   English   中英

Spring / Hibernate / Transaction同步問題

[英]Spring/Hibernate/Transaction synchronization issue

我有一項服務,可根據輸入日期返回持久化的Schedule對象。 我有多個線程調用此方法,並且我想確保唯一性。 我不想捕獲約束沖突並給任何用戶一個錯誤。 我需要的是:如果一個線程調用該方法,並且在那個日期不存在Schedule對象,那么該線程將創建該方法,而其他線程將等待。 在我使用Spring之前,在我的Web應用程序中只是普通的Hibernate,我已經通過以下方式做到了:

我已經在休眠狀態下使用了ManagedSessionContext。 我在每個Web請求的開始處開始一個事務,並在最后提交它。 對於同步塊,我已經在同步塊中立即提交了當前事務,並開始了一個新事務來完成請求。 我的隔離級別為READ_COMMITED,效果很好。

public synchronized Schedule getSchedule(Date date) {
  Schedule schedule = dao.getSchedule(date);
  if (schedule == null) {
    schedule = createSchedule(date);
    dao.save(schedule);
    HibernateUtils.getCurrentSession().getTransaction().commit();
    HibernateUtils.getCurrentSession().getTransaction().begin();

  }
  return schedule;
}

現在,我在這個項目中使用Spring,並且在事務管理中使用aop。 我已經刪除了手動交易代碼。 我正在測試多個線程,並且出現死鎖。原因:java.sql.SQLException:超出了鎖等待超時; 嘗試重新啟動事務

我的交易AOP:

<tx:advice id="txAdvice">
      <tx:attributes >
      <tx:method name="getSchedule" isolation="SERIALIZABLE" />
      <tx:method name="*" />
      </tx:attributes>
    </tx:advice>
@Autowire
private HibernateTransactionManager txManager;

用以下方法包裝方法主體:

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("transactionName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus ts = txManager.getTransaction(def);

//Body Code

txManager.commit(ts);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM