|
Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide
10g Release 3 (10.1.3) B14428-01 |
|
![]() Previous |
![]() Next |
You must implement an ejbFindByPrimaryKey method for a BMP entity bean (see "Implementing an EJB 2.1 BMP the ejbFindByPrimaryKey Method"). Optionally, you may configure other finders (see "Implementing Other EJB 2.1 BMP Finder Methods").
For more information, see "Using EJB 2.1 Query API".
The ejbFindByPrimaryKey implementation is a requirement for all BMP entity beans. Its primary responsibility is to ensure that the primary key corresponds to a valid bean. Once it is validated, it returns the primary key to the container, which uses the key to return the bean reference to the user.
This sample verifies that the employee number is valid and returns the primary key, which is the employee number, to the container. A more complex verification would be necessary if the primary key was a class.
public EmployeePK ejbFindByPrimaryKey(EmployeePK pk)
throws FinderException
{
if (pk == null || pk.empNo == null) {
throw new FinderException("Primary key cannot be null");
}
try {
conn = getConnection(dsName);
ps = conn.prepareStatement(findByPKStatement);
ps.setInt(1, pk.empNo.intValue());
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if (rs.next()) {
pk.empNo = new Integer(rs.getInt(1));
pk.empName = new String(rs.getString(2));
pk.salary = new Float(rs.getFloat(3));
} else {
throw new FinderException("Failed to select this PK");
}
} catch (SQLException e) {
throw new FinderException(e.getMessage());
} catch (NamingException e) {
System.out.println("Caught an exception 1 " + e.getMessage() );
throw new EJBException(e.getMessage());
} finally {
try {
ps.close();
conn.close();
} catch (SQLException e) {
throw new EJBException(e.getMessage());
}
}
return pk;
}
Optionally, you can create other finder methods in addition to the single ejbFindByPrimaryKey.
To create other finder methods, do the following:
Add the finder method to the home interface.
Implement the finder method in the BMP bean implementation.
Finders can retrieve one or more beans according to the WHERE clause. If more than a single bean is returned, then a Collection of primary keys must be returned by the BMP finder method. These finder methods need only to gather the primary keys for all of the entity beans that should be returned to the user. The container maps the primary keys to references to each entity bean within either a Collection (if multiple references are returned) or to the single class type.
The following example shows the implementation of a finder method that returns all employee records.
public Collection ejbFindAll() throws FinderException
{
ArrayList recs = new ArrayList();
ps = conn.prepareStatement("SELECT EMPNO FROM EMPLOYEEBEAN");
ps.executeQuery();
ResultSet rs = ps.getResultSet();
int i = 0;
while (rs.next())
{
retEmpNo = new Integer(rs.getInt(1));
recs.add(retEmpNo);
}
ps.close();
return recs;
}