我有一个会话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 > 1
,它会尝试创建具有相同ID的第二个bean(System.out.println(newID);
打印相同的值)。我猜测新bean尚未存储在数据库中,因此查询返回相同的值。可以做些什么?
非常感谢!
答案 0 :(得分: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();
}
}