【问题标题】:@transactional in spring jpa not updating tablespring jpa中的@transactional不更新表
【发布时间】:2014-10-06 11:41:04
【问题描述】:

我在我的项目中使用 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,但没有任何效果。我知道我在这里做错了,但无法弄清楚我到底在哪里做错了。谁能帮我解决这个问题

【问题讨论】:

  • 为什么你的方法既是同步的又是事务的?

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


【解决方案1】:

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

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

【讨论】:

  • 我已经删除了 childmethod1 中的 @transactional 并将 childmethod2() 移动到另一个类。仍然没有更新
  • 如果 childmethod1 是第一个调用的方法,它将不起作用。调用的第一个方法必须是带有注释的方法。
【解决方案2】:

在这种情况下我遵循的典型清单:

  1. 如果是基于 Java 的配置,请确保 类中存在@EnableTransactionManagement 注释 包含@Configuration 注解
  2. 确保创建了 transactionManager bean,这应该在配置类中再次提及。
  3. 在调用存储库的方法上使用@Transactional annocatio,通常是 DAO 层中的一个类
  4. 为调用存储库中方法的类添加@Service注解

很好的博客,它深入解释了使用 JPA 的事务配置 --> http://www.baeldung.com/2011/12/26/transaction-configuration-with-jpa-and-spring-3-1/68954

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多