我使用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.
}
}
如何解决以下问题:
答案 0 :(得分:0)
您可以在服务方法上使用@Transactional
来确保数据库操作在事务中运行。默认情况下,如果在带注释的方法中抛出未经检查的异常,则可以回滚事务。您还可以使用@Transactional
的rollbackFor Parameter
答案 1 :(得分:0)
不确定为什么你有一个删除方法基本上与SimpleJpaRepository删除方法完全相同,所以对于初学者我将你的代码改为
repo.delete(entityId)
并摆脱测试服务。
如果您担心在没有要删除的数据时获取EmptyResultDataAccessException,请捕获异常并忽略它或对其他正在执行删除操作使用悲观锁定,如解释 here
答案 2 :(得分:0)
您可以使用注释@Transaction进行服务方法删除(UUID id2)。@ Transaction的默认传播是Propagation.REQUIRED,这意味着如果您获得现有事务,它会继续,如果您没有现有事务,会为你创造一个。