ページの先頭行へ戻る
Interstage Application Server/Interstage Web Server J2EE ユーザーズガイド

21.3.4 JTAを利用したアプリケーション例

    /* 初期化処理  */
    javax.transaction.UserTransaction ut = null;
    javax.naming.Context ic = null;
    // InitialContextの生成
    try{
        ic = new InitialContext();・・・(1)
    } catch( NamingException e ) {
        System.out.println( "error: new InitialContext()" );
        System.exit(1);
    }
    // UserTransactionの獲得
    try {
        ut = (UserTransaction)ic.lookup(“java:comp/UserTransaction”);・・・(2)
    } catch( NamingException e ) {
        System.err.println( "error: lookup UserTransaction" );
        System.exit(1);
    }
    try {
        ut.begin();・・・(3)
    } catch (NotSupportedException e) {
        System.err.println("The thread is already associated with a transaction ");
        System.exit(1);
    } catch(SystemException e) {
        System.err.println("The system error has been encountered");
        System.exit(1);
    }
    
    try {
        //ビジネスロジックを記述します。・・・(4)
    } catch(Throwable e) {
        // ここでは例として処理が失敗した場合にフラグをfalseに設定しています。
        commitRequest = false;
    }
    
    if(commitRequest) {・・・(5)
        try {
            ut.commit();・・・(6)
        } catch(RollbackException e) {
            System.err.println("The transaction has been rolled back rather than committed");
        } catch(SystemException e) {
            System.err.println("The system error has been encountered.");
        }
    } else {
        try {
            ut.rollback();・・・(6)
        } catch(java.lang.IllegalStateException e) {
            System.err.println("The current thread is not associated with a transaction.");
        } catch(SystemException e) {
            System.err.println("The system error has been encountered.");
        }
    }
  1. JNDIを使用するためにInitialContextを生成します。

  2. javax.transaction.UserTransactionオブジェクトをJNDIから獲得します。

  3. javax.transaction.UserTransaction.beginメソッドでトランザクションを開始します。

  4. ビジネス処理を記述します。

  5. コミット可能かどうか確認して、トランザクションの状態を決定します。

  6. トランザクションを確定終了させる場合はcommitメソッドでトランザクションをコミットさせます。

  7. 異常によりコミットすべきでない場合は、rollbackメソッドでトランザクションをロールバックさせます。

ポイント

JNDIの詳細については、“第4章 JNDI”を参照してください。