簡體   English   中英

Spring JPA中的@transactional不更新表

[英]@transactional in spring jpa not updating table

我在項目中使用spring jpa事務。一個案例包括在同步方法中插入數據,當另一個線程訪問它時數據未更新,我的代碼如下:

public UpdatedDTO parentMethod(){
  private UpdatedDTO updatedDTO = getSomeMethod();
  childmethod1(inputVal);
  return updatedDTO;
}

@Transactional
public synchronized  childmethod1(inputVal){
 //SomeCodes

 //Place where update takes place
 TableEntityObject obj = objectRepository.findByInputVal(inputVal);
 if(obj == null){
    childMethod2(inputVal);
  }

}

@Transactional
public void childMethod2(inputVal){

//Code for inserting
TableEntityObject obj = new TableEntityObject();
obj.setName("SomeValue");
obj.setValueSet(inputVal);
objectRepository.save(obj);
}

現在,如果兩個線程同時訪問,並且第一個線程完成了childmethod2和childmethod1的操作,並且之后沒有完成parentMethod()的工作,那么如果第二個線程進入childMethod1()並檢查數據是否存在,則該數據為null且不首先更新我嘗試了很多方法

@Transactional(propagation = Propagation.REQUIRES_NEW)
public synchronized  childmethod1(inputVal){
 //SomeCodes

 //Place where update takes place
 TableEntityObject obj = objectRepository.findByInputVal(inputVal);
 if(obj == null){
    childMethod2(inputVal);
  }

} 

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void childMethod2(inputVal){

//Code for inserting
TableEntityObject obj = new TableEntityObject();
obj.setName("SomeValue");
obj.setValueSet(inputVal);
objectRepository.save(obj);
}

我也嘗試在childMethod1()中取消@transactional,但沒有任何解決方法。我知道我在這里做錯了什么,但無法弄清楚我到底在哪里做錯什么。

@Transactional通過使用Spring Bean上的代理來解決。 這意味着,如果從同一類調用帶有@Transactional的方法,則該方法無效。 看一看Spring @Transaction方法在同一個類中被該方法調用,行不通嗎?

最簡單的方法是將這些方法轉移到單獨的服務中。

在以下情況下,我會遵循典型的清單:

  1. 如果基於Java的配置,請確保包含@Configuration批注的類中存在@EnableTransactionManagement注釋
  2. 確保已創建transactionManager bean,這又應在配置類中提及。
  3. 在調用存儲庫的方法(通常是DAO層中的類)上使用@Transactional通知
  4. 為正在調用存儲庫中方法的類添加@Service批注

尼斯博客,深入解釋了使用JPA的事務配置-> http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/68954

暫無
暫無

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

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