1

我有一个提供业务方法的会话 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();
    }
}

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

非常感谢!

4

1 回答 1

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();
    }
}
于 2010-08-09T16:14:19.177 回答