Writing the Primary Key Class


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

  • Implement java.io.Serializable .

  • Be constructed with the public default constructor (no parameters).

  • Contain a public attribute that has the same name and type as the primary key attribute in the entity bean.

  • Override the equals() method to compare based on the primary key attribute.

  • Override the hashCode() method to generate the hashcode based on the value of the primary key.

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 Class

The 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();     } } 


BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net