views:

31

answers:

1

Hello, I have a session bean that provides a business method, in which it creates several CMP entity beans, something like this

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();
    }
}

The create method of MyBean simply creates a new bean with newID. However, the above code only works with number = 1. If number > 1, it tries to create a second bean with the same ID (System.out.println(newID); prints the same value). I'm guessing the new bean is not stored in the database yet, and thus the query returns the same value. What can be done to this?

Many thanks!

A: 

I figured it out that the transaction is only executed when the business method finishes, so the first entity beans would not be stored in the database for retrieval. A simple solution is below

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();
    }
}
phunehehe