【问题标题】:when is an EJB CMP entity bean actually created何时实际创建 EJB CMP 实体 bean
【发布时间】:2010-08-05 15:35:04
【问题描述】:

我有一个提供业务方法的会话 bean,它在其中创建几个 CMP 实体 bean,类似这样

public void businessMethod(int number) {
    try {
        MyBeanHome home = lookupMyBean();
        DataSource dataSource = getMyDataSource();
        Statement statement = dataSource.getConnection().createStatement();
        ResultSet result;
        String tableName = "MYBEAN";
        for (int i = 0; i < number; i++) {
            result = statement.executeQuery("select max(ID) + 1 from " + tableName);
            result.next();
            int newID = result.getInt(1);
            System.out.println(newID);
            MyBeanLocal lineLocal = home.create(newID);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

MyBean 的 create 方法只是用newID 创建一个新的 bean。但是,上面的代码只适用于number = 1。如果number &gt; 1,它会尝试创建第二个具有相同ID 的bean(System.out.println(newID); 打印相同的值)。我猜新 bean 还没有存储在数据库中,因此查询返回相同的值。对此有什么办法?

非常感谢!

【问题讨论】:

    标签: sql persistence ejb cmp entity-bean


    【解决方案1】:

    我发现事务仅在业务方法完成时执行,因此第一个实体 bean 不会存储在数据库中以供检索。下面是一个简单的解决方案

    public void businessMethod(int number) {
        try {
            MyBeanHome home = lookupMyBean();
            DataSource dataSource = getMyDataSource();
            Statement statement = dataSource.getConnection().createStatement();
            ResultSet result;
            String tableName = "MYBEAN";
            result = statement.executeQuery("select max(ID) + 1 from " + tableName);
            result.next();
            int newID = result.getInt(1);
            for (int i = 0; i < number; i++) {
                System.out.println(newID);
                MyBeanLocal lineLocal = home.create(newID++);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多