/* 初期化処理 */ 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(); (7) } 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."); } }
JNDIを使用するために、InitialContextを生成します。
JNDIからjavax.transaction.UserTransactionオブジェクトを獲得します。
javax.transaction.UserTransaction.beginメソッドでトランザクションを開始します。
ビジネス処理を記述します。
コミット可能かを確認して、トランザクションの状態を決定します。
トランザクションを確定終了させる場合は、commitメソッドでトランザクションをコミットさせます。
異常によりコミットすべきではない場合、rollbackメソッドでトランザクションをロールバックさせます。
ポイント
JNDIの詳細については、“第4章 JNDI”を参照してください。