【问题标题】:JPA Toplink - what is the need of checking active transaction in the beginning of process?JPA Toplink - 在流程开始时检查活动事务的需要是什么?
【发布时间】:2011-06-26 21:02:45
【问题描述】:

我在互联网上看到很少有样本可以在流程开始时检查交易当前是否处于活动状态。

下面的代码是我从工厂获取 EntityManager 的。

我不明白为什么需要在开始之前检查交易是否处于活动状态???

是不是因为其他一些进程可能正在使用同一个 EntityManager 实例? (EntityManagerFactory 是单例但 EntityManager 不是)

    @Path("update")
    @PUT
    @Consumes("application/json")
    public Response machineUpdate(String content) {
        JSONObject jObj = null;
        EntityManager em = null;
        EntityTransaction txn = null;

        try {

           JSONObject jObj = new JSONObject(content);
           em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();

           //what's this line doing here???
           if(em.getTransaction().isActive()) {
               return HttpStatusHandler.sendConflict();
           }

           txn = em.getTransaction();
           txn.begin();
          //more process ......
        }
        catch(.....

【问题讨论】:

    标签: java jpa transactions entitymanager toplink-essentials


    【解决方案1】:

    我看不出任何需要进行事务检查的理由,因为代码使用的是 JPA 事务 API,鉴于刚刚创建了 EntityManager,因此无法激活事务。

    如果您使用的是 JTA 托管的 EntityManager,那么 JTA 事务可能已经处于活动状态。但是对于 JTA,您不能使用 JPA Transaction 开始事务,您可以使用 JTA 开始事务,或者在 JPA 中使用 joinTransaction()。

    【讨论】:

    • 我没有使用 JTA(在persistences.xml 中禁用),但根据我的研究和您的声明,不需要在开头检查 isActive(),谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多