Sometimes you may want to to retrieve multiple entity beans without performing multiple JNDI lookup calls. This can be made via finder methods of the home interface which returns a collection of EJB references.

Returning a collection of data requires you to add some specific helper methods to the EJB home interface. In the home interface of a bean, define a finder method that returns a java.util.Collection instance instead of a single instance of an entity bean.

In this tip we describe BMP bean; its finder method returns a Collection of the primary keys for the entity bean matching. The container will replace each primary key with the entity bean instance it represents.

A home interface with finder:

 public interface PersonBeanHome extends EJBHome {
    public PersonBean create(PersonKey holding)
       throws CreateException, RemoteException;
    public PersonBean findByPrimaryKey(PersonKey primaryKey)
       throws FinderException, RemoteException;
    // our own finder method, searching persond by the first name:
    public Collection findByFirstName(String firstName)
       throws FinderException, RemoteException;

A corresponding bean code:
public abstract class PersonBean implements EntityBean {
    public Collection ejbFindByFirstName(String firstName)
            throws ObjectNotFoundException {
        ArrayList array = new ArrayList();
        try {
            Connection conn = getConnection();
            Statement st = conn.createStatement(
                    "SELECT firstName, lastName FROM personTable " +
                    "WHERE firstName = " + firstName);
            ResultSet rs = ps.getResultSet();
            while ( {
                // we have a contructor there: PersonKey(firstName, lastName):
                array.add(new PersonKey(rs.getString(1), rs.getString(2)));
        } catch (SQLException sqe) {
            throw new EJBException(sqe);
        } finally {
            // release DB-connection...
        return array;