コンテナ管理の関連(CMR)の一部の操作は、トランザクションのコンテキストでのみ有効です。
たとえば、1対Nの関連を持つ2つのCMP Bean(DepartmentsおよびEmployees)があり、ある従業員を部門20から部門10に移動しようとすると、トランザクションのコンテキスト内で行う場合を除き、エラーとなります。
トランザクションでこの操作を行うには、次の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(); }
コンテナ・トランザクション・エントリを追加するには、次のようにします。
Enterprise JavaBeansのモデルの作成
Enterprise JavaBeansの開発