实体Bean的主键类


在部署实体Bean时,你必须在部署描述符指定主键类型。很多时候,主键类型可能是String、Integer或者其他J2SE或J2EE标准库中的类。但是有很多实体Bean的主键是复合字段,你必须自己定义主键类。

主键类


  下面的主键类是一个复合组建类,productId和vendorId字段共同标志一个唯一的实体:


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.concat(vendorId).hashCode();


}


}


  对BMP,主键类规则如下:


  1. 主键类必须是公有(public)类


  2. 所有数据成员都是共有(public)的


  3. 有一个共有(public)的缺省构造函数


  4. 重载hashCode()和equals(Object other)方法


  5. 可序列化


实体Bean类中的主键


  在BMP中,ejbCreate方法将传入参数赋值给对应字段并返回主键类


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


}


  ejbFindByPrimaryKey核实传入主键值在数据库中是否存在对应纪录:


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;


}


获取主键


  客户端可以调用EJBObject(远程接口)对象的getPrimaryKey方法得到实体Bean得主键值:


SavingsAccount account;


...


String id = (String)account.getPrimaryKey();


实体Bean调用EntityContext对象的getPrimaryKey方法找回自己的主键值:


EntityContext context;


...


String id = (String) context.getPrimaryKey();

没有评论: