我最近遇到了 Play Framework 2 @Transactional 的问题。根据我的测试,在发生异常的情况下,只有在未检查异常(没有 catch block )的情况下,事务方法才会回滚。 这是我的 Controller :
@Transactional
public Result myController(){
ObjectNode result = Json.newObject();
try{
JsonNode json = request().body().asJson();
someFunction(json);
//doing some stuff using the json object inside someFunction
//which I may intentionally throw an exception
//based on some logic from within
//(using "throw new RuntimeException()")
result.put("success", true);
return ok(Json.toJson(result));
}catch(Exception e){
result.put("success", false);
result.put("msg", e.getMessage());
return internalServerError(Json.toJson(result));
}
}
我希望我的 Controller 始终返回 JSON 作为响应。但这是以当我在代码中抛出异常时没有数据库回滚为代价的。我知道在 Spring 你可以将其添加到 @Transactional 注释,但我正在使用 play.db.jpa.Transactional。有什么方法可以在不使用 spring 的情况下在 catch block 中进行回滚吗?
最佳答案
@Transactional
注释基本上将操作的代码包装在对 DefaultJpaApi.withTransaction
的调用中。如果你看the source您可以看到该方法如何处理事务。
由于您想捕获异常,但仍想使用 withTransaction
行为,您可以尝试删除 @Transactional
注释并调用 withTransaction
code> 自己在操作中。
例如
class MyController {
private final JPAApi jpa;
@Inject
public MyController(JPAApi jpa) {
this.jpa = jpa;
}
public myAction() {
ObjectNode result = Json.newObject();
try {
JsonNode json = request().body().asJson();
// Calls someFunction inside a transaction.
// If there's an exception, rolls back transaction
// and rethrows.
jpa.withTransaction(() -> someFunction(json));
// Transaction has been committed.
result.put("success", true);
return ok(Json.toJson(result));
} catch(Exception e) {
// Transaction has been rolled back.
result.put("success", false);
result.put("msg", e.getMessage());
return internalServerError(Json.toJson(result));
}
}
}
关于java - 如何回滚 Play 框架中捕获的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47319739/