CMR操作の使用方法

コンテナ管理の関連(CMR)の一部の操作は、トランザクションのコンテキストでのみ有効です。

たとえば、1対Nの関連を持つ2つのCMP Bean(DepartmentsおよびEmployees)があり、ある従業員を部門20から部門10に移動しようとすると、トランザクションのコンテキスト内で行う場合を除き、エラーとなります。

トランザクションでこの操作を行うには、次の2つの方法があります。

トランザクション・コンテキストを手動で追加するには、次のようにします。

  1. ウィザードを使用してJSPを作成します。
  2. 次のようなコードを使用して、トランザクションを開始します。

    try {
      Context context = new InitialContext();
      UserTransaction ut=
       (UserTransaction)context.lookup("java:comp/UserTransaction");
    
    ut.begin();
      LocationsLocalHome LocationsHome =
       (LocationsLocalHome)(context.lookup("java:comp/env/Locations"));
      DepartmentsLocalHome DepartmentsHome =
       (DepartmentsLocalHome)(context.lookup("java:comp/env/Departments"));
    
      LocationsLocal Locations;
      DepartmentsLocal Departments;
    
      Locations = LocationsHome.findByPrimaryKey(new Long(1700));
      Departments = DepartmentsHome.findByPrimaryKey(new Long(11));
    
      Departments.setLocations_location_id(Locations);
    
      // out.println("ename = " + Locations.getEname());
    
      Collection coll = Locations.getDepartments_location_id();
      Iterator iter = coll.iterator();
    
      while (iter.hasNext())
      {
        Departments = (DepartmentsLocal)iter.next();
        out.println("D = " + Departments.getDepartment_id());
        out.println();
      }
    
    ut.commit();
      }
    
      catch (Throwable ex)
      {
        ex.printStackTrace();
      } 

コンテナ・トランザクション・エントリを追加するには、次のようにします。

  1. EJBモジュール・エディタで、CMP BeanをコールするセッションBeanを開きます。
  2. コンポーネント・インタフェース・メソッドをセッションBeanに追加します。
  3. EJBモジュール・エディタのナビゲーション・ペインで、「コンテナ・トランザクション属性」をクリックします。
  4. 「追加」をクリックし、新規のコンテナ・トランザクションを作成します。
  5. 「メソッド」リストで、作成したメソッドをクリックします。「OK」をクリックします。
  6. 「トランザクション属性」フィールドをクリックし、「Required」を選択します。
  7. 「OK」をクリックします。

関連項目

Enterprise JavaBeansのモデルの作成
Enterprise JavaBeansの開発