欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot手動事務(wù)回滾的實(shí)現(xiàn)代碼

 更新時(shí)間:2020年07月24日 10:32:07   投稿:mrr  
這篇文章主要介紹了springboot手動事務(wù)回滾的實(shí)現(xiàn)方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

親測在使用@Transactional、@Transactional(rollbackFor = Exception.class)及catch異常之后 throw new RuntimeException();仍然不能解決線程中的事務(wù)回滾。下面使用線程所機(jī)制,進(jìn)行整體的事務(wù)提交及事務(wù)回滾,代碼如下:

在springboot啟動類上加  @EnableTransactionManagement  注解

線程類中添加以下代碼

@Autowired
  private PlatformTransactionManager platformTransactionManager;
  @Autowired
  private TransactionDefinition transactionDefinition;
  private Lock lock = new ReentrantLock();
  // todo 業(yè)務(wù)處理方法 數(shù)據(jù)存儲異常 手動進(jìn)行回滾
  public void saveMsg(String message) throws Exception {
    lock.lock();
    TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
    try {
    	//todo 具體業(yè)務(wù),對數(shù)據(jù)庫的操作 start
    	test1Service.save(test1);
    	test2Service.save(test2);
    	//end
    	
      platformTransactionManager.commit(transaction);
    } catch (Exception e) {
      platformTransactionManager.rollback(transaction);
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

注:如果無法用 @Autowired 程序啟動進(jìn)行對象創(chuàng)建,可以使用init靜態(tài)注入,如果對象可以正常創(chuàng)建,下面代碼可以忽略。

@Autowired
  private static PlatformTransactionManager platformTransactionManager;
  @Autowired
  private static TransactionDefinition transactionDefinition;

  @Autowired
  public void init(PlatformTransactionManager platformTransactionManager,TransactionDefinition transactionDefinition
  ) {
    DriverAlfaServerHandler.platformTransactionManager = platformTransactionManager;
    DriverAlfaServerHandler.transactionDefinition = transactionDefinition;
  }

此回滾方法親測有效。

到此這篇關(guān)于springboot手動事務(wù)回滾的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)springboot 事務(wù)回滾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論