2

プロセスの開始時にトランザクションが現在アクティブであるかどうかをチェックするサンプルをインターネットでいくつか見ました。

以下のコードは私のもので、ファクトリからEntityManagerを取得します。

begin()を実行する前に、トランザクションがアクティブであるかどうかを確認する必要がある理由がわかりません。

他のプロセスが同じ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(.....
4

1 に答える 1

2

コードがJPAトランザクションAPIを使用しているため、トランザクションチェックの理由がわかりません。EntityManagerが作成されたばかりの場合、トランザクションをアクティブにする方法はありません。

JTA管理のEntityManagerを使用していた場合、JTAトランザクションはすでにアクティブになっている可能性があります。ただし、JTAの場合、JPAトランザクションを使用してトランザクションを開始することはできません。JTAを使用してトランザクションを開始するか、JPAでjoinTransaction()を使用する必要があります。

于 2011-02-14T14:27:33.347 に答える