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

21.3.3 トランザクションの開始から完了まで

UserTransactionインタフェースを利用してトランザクションを開始するにはbeginメソッドを発行します。

UserTransactionインタフェースを利用してトランザクションを完了するにはcommitメソッドかrollbackメソッドを発行します。commitメソッドは処理を確定し、rollbackメソッドは処理を取り消します。

処理の記述例を以下に示します。

    // UserTransactionの獲得
    try {
        ut = (UserTransaction)ic.lookup(“java:comp/UserTransaction”);
    } catch( NamingException e ) {
        System.err.println( "error: lookup UserTransaction" );
        System.exit(1);
    }
    try {
        ut.begin();
    } 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 {
        //ビジネスロジックを記述します。
    } catch(Throwable e) {
        // ここでは例として処理が失敗した場合にフラグをfalseに設定しています。
        commitRequest = false;
    }
    
    if(commitRequest) {
        try {
            ut.commit();
        } 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();
        } 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.");
        }
    }