【问题标题】:How to implement Transactional for multiple updates in single method Springboot JPA如何在单一方法Springboot JPA中实现多个更新的事务
【发布时间】:2021-11-21 20:47:33
【问题描述】:

我有一个使用 SPringboot JPA 对 DB 进行多次更新、删除和保存方法调用的方法。这些更新、删除和保存方法中的每一个都用@Transactional 修饰。 如何在我的 userdefined_method() 上实现 Transactinal?这样所有在后续方法发生任何故障的情况下都会恢复以前的方法更改。

private void userdefined_method(){
    // part1 few lines of business logic code 
    orderService.deleteById(123);  // these methods are decorated with @Transactional
    //part2 few lines of business logic code
    orderservice.save(order);   // this method is decorated with @Transactional
    //part 3 few more lines of business logic

}

在此示例中,已调用 deleteById 并从表中删除了 Entry,并假设 part2 中存在错误,或者 save(order) 方法中存在错误,应回滚先前的删除语句。

【问题讨论】:

标签: java spring-boot spring-data-jpa transactions


【解决方案1】:

你可以把@Transactional放在方法上,把private改成public

@Transactional
public void userdefined_method(){
    // part1 few lines of business logic code 
    orderService.deleteById(123);  // these methods are decorated with @Transactional
    //part2 few lines of business logic code
    orderservice.save(order);   // this method is decorated with @Transactional
    //part 3 few more lines of business logic

}

关于@Transactional的解释可以看看这个link

【讨论】:

  • 但是这个类没有扩展 CrudRepository,使用@Transactional。我尝试使用 Transactional 来查看它是否有效,但在 Part2 业务逻辑中出现问题时无法回滚 deletedById
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2019-12-30
相关资源
最近更新 更多