java - 如何回滚 Play 框架中捕获的异常?

标签 java hibernate jpa playframework transactions

我最近遇到了 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/

相关文章:

java - 创建 "Service"bean 时出错

java - 纹理包裹,奇怪的边缘

java - 使用 Hibernate,拦截器接收与当前值和先前值相同的集合对象,如何获取真实的当前值和先前值?

java - 在java中用不同的用户调用外部进程

java - 在公共(public)表保存多个表的元数据的情况下使用 Hibernate

java - 如何从 JPA EntityManager 获取返回的对象作为自定义 bean

java - ManyToMany HQL Join - 连接的预期路径

java - JPA 实体 ID 问题

java - 删除父项后如何存储受影响的值

java - 使用 http 客户端发布 tar.gz 文件时出错,但使用 curl 命令可以正常工作