在Spring中创建一个事务方法

时间:2018-02-15 13:56:50

标签: spring hibernate spring-boot spring-data

我使用hibernate作为JPA提供程序

@RestController
public class RestController {
    private final TestService testService;

    @PostMapping(value = "/file/{entityId}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void test(@PathVariable @NotNull UUID entityId) {
        testService.delete(entityId);
    }
}

class TestService {
    @AutoWired
    EntityRepository repo; // <- Crud repository from Spring Data

    public void delete(UUID id2){
        //if row not exists with id == id2 
            throw NoFoundException
        // else
            //remove from database using repo.
    }
}

如何解决以下问题:

  1. “如果不存在id == id2的行”,则评估为false,因为对象实际存在。
  2. 其他帖子删除了该行。
  3. “使用repo从数据库中删除”&lt; - 错误,没有这样的行,因为它在步骤2中被其他线程删除了。

3 个答案:

答案 0 :(得分:0)

您可以在服务方法上使用@Transactional来确保数据库操作在事务中运行。默认情况下,如果在带注释的方法中抛出未经检查的异常,则可以回滚事务。您还可以使用@Transactional的rollbackFor Parameter

指定要回滚的例外

答案 1 :(得分:0)

不确定为什么你有一个删除方法基本上与SimpleJpaRepository删除方法完全相同,所以对于初学者我将你的代码改为

repo.delete(entityId)

并摆脱测试服务。

如果您担心在没有要删除的数据时获取EmptyResultDataAccessException,请捕获异常并忽略它或对其他正在执行删除操作使用悲观锁定,如解释 here

答案 2 :(得分:0)

您可以使用注释@Transaction进行服务方法删除(UUID id2)。@ Transaction的默认传播是Propagation.REQUIRED,这意味着如果您获得现有事务,它会继续,如果您没有现有事务,会为你创造一个。