簡體   English   中英

循環傳播新事務(使用REQUIRES_NEW)不能按預期方式進行

[英]Propagation of new transactions (using REQUIRES_NEW) in a loop is not working as expected

我不確定以下原因為何不起作用。 我希望新事務以循環開始(傳播= REQUIRES_NEW)。 並且在此循環中觸發新事務之前,應提交每個事務。 但是,僅執行循​​環的第一次迭代,然后什么也沒有發生。

   @Service
    @Transactional
    public class Aimpl implements A {

    @Autowired
    private B b;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

      public void methodA(List<Customer> customers){
       logger.info("before loop"); //gets printed
       customers.forEach(customer -> {
         logger.info("1"); //--> this gets printed
         b.processEachCustomer(customer);
         logger.info("2"); //- this does not get printed 
         });
         logger.info("after loop"); //does not get printed
      }
    }

//-----------------Second class----------


 @Service
    @Transactional
    public class Bimpl implements B {

     @Autowired
     private MyRepository repository;

     private Logger logger = LoggerFactory.getLogger(this.getClass());

      @Transactional(propagation = Propagation.REQUIRES_NEW)
      public void processEachCustomer(Customer customer){

        //process each customer - a new transaction everytime 
       //and it should be committed independently
       repository.updateCustomerData(customer.getId());
       logger.info("3");//this does not get printed
      }
    }

這是我的存儲庫類,它僅在表中針對一行發出更新查詢。

public interface MyRepository extends Repository<Customer , Long> {

    @Modifying
    @Query("UPDATE Customer c SET c.status = 1 WHERE i.id= :id")
    int setStatusById(@Param("id") Integer id);

}

我在這里做錯了什么? 基本上,為什么只有循環的第一次迭代才起作用,而其余的為什么不起作用? 我正在嘗試調試它,並且看不到應用程序在第一次迭代后在斷點處停止。

方法A將使用默認范圍創建事務,因為@Transactional在類級別。

當我從methodA()中刪除注釋,並且還刪除了類Aimpl中的類級別事務性注釋時,此方法運行良好。

 @Service
    public class Aimpl implements A {

    @Autowired
    private B b;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

      public void methodA(List<Customer> customers){
       customers.forEach(customer -> {
         b.processEachCustomer(customer);
         });
      }
    }

// -----------------第二類----------

@Service
@Transactional
public class Bimpl implements B {

 @Autowired
 private MyRepository repository;

 private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void processEachCustomer(Customer customer){

    //process each customer - a new transaction everytime 
   //and it should be committed independently
   repository.updateCustomerData(customer.getId());
  }
}

編輯2:讓我在這里糾正自己。 即使我不從方法中刪除事務性注釋並使類保持事務性注釋,此方法也能正常工作。 真正的問題是死鎖,由於其他進程獲取的鎖,該死鎖正在數據庫級別發生。 該代碼是正確的。

暫無
暫無

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

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