@transactional在spring jpa没有更新表

时间:2014-10-06 11:41:04

标签: spring hibernate jpa web spring-data-jpa

我在我的项目中使用spring jpa事务。一个Case包括在synchronized方法中插入数据,当另一个线程访问它时,数据不会更新。我的代码如下:

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,但没有任何效果。我知道我在这里做错了什么,但无法弄清楚我在做错的地方和地点。任何人都可以帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

使用spring bean上的代理解析@Transactional。这意味着如果从同一个类调用带有@Transactional的方法,它将无效。看看Spring @Transaction method call by the method within the same class, does not work?

最简单的方法是将这些方法转移到单独的服务中。

答案 1 :(得分:0)

我遵循的典型清单如下:

  1. 如果基于Java的配置,请确保 @EnableTransactionManagement annocation存在于类中 包含@Configuration批注
  2. 确保创建了transactionManager bean,这应该在配置类中提及。
  3. 对调用存储库的方法使用@Transactional annocatio,通常是DAO层中的类
  4. 为正在调用存储库中的方法的类添加@Service注释
  5. 尼斯博客深入解释了JPA的交易配置 - > http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/68954