Entity EJBs must include a primary key that is used to uniquely identify an instance of the entity bean. The entity bean returns an instance of the primary key class from the ejbCreate() method. The primary key class may be a standard Java class, such as java.lang.String or java.lang.Integer . The bean provider may optionally provide a specific primary key class. The naming convention for the primary key class is to add the letters PK to the end of the remote interface name . The primary key for BookEntity is therefore BookEntityPK . The following rules must be followed when implementing a specific primary key class; it must
Tip If the EJB deployment descriptor uses <automatic-key-generation> , the primary key type must be java.lang.Integer . Do not write a specific primary key class for the entity bean if you intend to use automatic key generation. This option is explained in the section, "The weblogic-cmp-rdbms-jar.xml Persistence Descriptor" later in this chapter. Creating the BookEntityPK Primary Key ClassThe primary key for BookEntity is the bookId field, which is a String . The implementation for the specific primary key class for BookEntity contains the bookId as a public attribute and overrides the equals() and hashCode() methods . Listing 21.10 shows the implementation of the primary key class for the BookEntity EJB. Listing 21.10 Sample Primary Key Class for the BookEntity EJB/** * Primary Key for the BookEntity EJB */ package com.objectmind.BookStore; import java.io.Serializable; public class BookEntityPK implements Serializable { // primary key attribute public String bookID; /** * override equals() to compare against bookId */ public boolean equals( Object that ) { if((that == null ) !(that instanceof BookEntityPK)) return false; return bookID.equals( ((BookEntityPK)that).bookID ); } /** * override hashCode() */ public int hashCode() { return bookID.hashCode(); } } |