| Prev | Next | J2EETM Developer's Guide
Entity Beans |
ProductEJB bean, for example, you would specify a java.lang.String as the primary key class. In most cases, your primary key class will be a String or some other class that belongs to the java package.
productId and vendorId fields together uniquely identify an entity bean:
public class ItemKey implements java.io.Serializable {
public String productId;
public String vendorId;
public ItemKey() { };
public ItemKey(String productId, String vendorId) {
this.productId = productId;
this.vendorId = vendorId;
}
public String getProductId() {
return productId;
}
public String getVendorId() {
return vendorId;
}
public boolean equals(Object other) {
if (other instanceof ItemKey) {
return (productId.equals(((ItemKey)other).productId)
&& vendorId.equals(((ItemKey)other).vendorId));
}
return false;
}
public int hashCode() {
return productId.hashCode();
}
}
public.public.public default constructor.hashCode() and equals(Object other) methods.ejbCreate method returns the primary key class:
public ItemKey ejbCreate(String productId, String vendorId,
String description) throws CreateException {
if (productId == null || vendorId == null) {
throw new CreateException(
"The productId and vendorId are required.");
}
this.productId = productId;
this.vendorId = vendorId;
this.description = description;
return new ItemKey(productId, vendorId);
}
The ejbFindByPrimaryKey verifies the existence of the database row for the given primary key:
public ItemKey ejbFindByPrimaryKey(ItemKey primaryKey)
throws FinderException {
try {
if (selectByPrimaryKey(primaryKey))
return primaryKey;
. . .
}
private boolean selectByPrimaryKey(ItemKey primaryKey)
throws SQLException {
String selectStatement =
"select productid " +
"from item where productid = ? and vendorid = ?";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setString(1, primaryKey.getProductId());
prepStmt.setString(2, primaryKey.getVendorId());
ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
return result;
}
ejbCreate method returns null. (With bean-managed persistence, it returns an instance of the primary key class.)
With container-managed persistence, you do not have to write the code for the ejbFindByPrimaryKey method. (For more information, see the section, The Finder Methods on page 61.)
To create an container-managed entity bean with the ItemKey class example, in the Entity Settings dialog of the New Enterprise Bean Wizard you would specify these settings:
productId, vendorId, description).ItemKey.getPrimaryKey method of the EJBObject class:
The entity bean retrieves its own primary key by calling theAccount account; . . . String id = (String)account.getPrimaryKey();
getPrimaryKey method of the EntityContext class:
EntityContext context; . . . String id = (String) context.getPrimaryKey();