Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Specifying a BMP Entity Bean

Following the pattern of Session beans, specifying an Entity bean involves defining the local-home and the local interface:

  • The local-home interface extends javax.ejb.EJBLocalHome.

  • The local interface extends javax.ejb.EJBLocalObject.

A discussion on each of these interfaces follows.

Local-Home Interface

Listing 6.1 shows the complete JobLocalHome interface as an example.

Listing 6.1—JobLocalHome Interface

  1: package data;
  2: 
  3: import java.rmi.*;
  4: import java.util.*;
  5: import javax.ejb.*;
  6: 
  7: public interface JobLocalHome extends EJBLocalHome
  8: {
  9: 	JobLocal create (String ref, String customer) throws CreateException;
 10: 	JobLocal findByPrimaryKey(JobPK key) throws FinderException;
 11: 	Collection findByCustomer(String customer) throws FinderException;
 12: 	Collection findByLocation(String location) throws FinderException;
 13: 	void deleteByCustomer(String customer); 
 14: }

Each of these methods has a corresponding method in the bean class itself. Taking the JobBean code as an example:

  • The create(String ref, String customer) method in JobBean corresponds to ejbCreate(String ref, String customer) in the JobLocalHome interface.

  • The ejbFindByPrimaryKey(String name) method in JobBean corresponds to findByPrimaryKey(String name) in the JobLocalHome interface.

  • The ejbFindByCustomer() method in JobBean corresponds to findbyCustomer() in the JobLocalHome interface.

  • The ejbHomeDeleteByCustomer(String customer) in JobBean corresponds to deleteByCustomer(String customer) in the JobLocalHome interface.

Note

Note that for home methods, the convention is to append ejbHome, not just ejb, to the bean's method name.

This seems straight-forward enough, but note that the return types of for the bean's ejbCreate() and ejbFindXxx() methods are different from the return types of the methods in the local-home interface. Specifically, while the bean returns (to the EJB container) either primary key objects or Collections of primary key objects, the local-home interface methods return (to the client) either local proxies (that is, instances of objects that implement the JobLocal interface, for the example) or Collections of such.

Create and Remove Methods

The list of exceptions thrown by the local-home methods and the bean's corresponding methods should match in each case. For the createXXX() method, the list should be the union of the exceptions thrown by both ejbCreateXXX() and ejbPostCreateXXX(). If a home and a remote interface are being provided for the Entity bean, the java.rmi.RemoteException must be declared for the methods of the home interface.

As well as the create() method, the local-home interface inherits a remove(Object o) method from javax.ejb.EJBLocalHome. This corresponds to the ejbRemove() lifecycle method of the bean itself.

Finder Methods

Finder methods in the bean return either a single primary key (if a single bean matches the underlying query) or a java.util.Collection of primary keys (if there is more than one matching bean). The ejbFindByPrimaryKey() method is always required to be one of the bean's methods, al though it is not part of the EntityBean interface. This is because the argument type and return type will depend upon the bean.

NOTE

It is also possible for finder methods to return java.util.Enumerations. This dates from EJB 1.0 before the Java Collections API was introduced in J2SE 1.2 and should not be used.

Obviously, to specify the findByPrimaryKey() method, the primary key of the Entity bean must have been identified. As was noted earlier today, if persisting to an RDBMS, identifying the primary key is probably quite easy, because the primary key will correspond to the columns of the primary key of the underlying RDBMS table. A custom-developed primary key class is needed when two or more fields identify the bean; otherwise, the type of the single field of the bean that represents the key is used.

NOTE

If a single field of the bean is used as the primary key, that field must not be a primitive type (such as an int or long). Primary key fields must be actual classes, such as a java.lang.String. Furthermore, the EJB specification does not allow primary keys to change once assigned, so it is best if the class chosen is immutable.

Custom Primary Key Classes

As noted earlier, the primary key can be either a field of the bean (in which case, the primary key class is just the class of that field) or can be a custom-developed class. The latter is required if more than one field is needed to identify the bean (and can be used even for single field keys).

For the JobBean, the primary key is a combination of the customer and the job reference (the customer and ref fields, respectively). Because the primary key is composite, a custom primary key class is needed; this is the JobPK class.

Custom primary key classes are required to follow a number of rules. Specifically

  • The class must implement java.io.Serializable or java.io.Externalizable.

  • The values of the class must all be primitives or be references to objects that, in turn, are serializable.

  • The equals() method and the hashCode() methods must be implemented.

  • There must be a no-arg constructor (there can also be other constructors that take arguments, but they would only be provided for convenience).

In other words, the class must be what is sometimes referred to as a value type.

NOTE

At least conceptually, value types are immutable (there should be no setter methods; they cannot be changed). The requirement for a no-arg constructor does prevent this from actually being the case.

Listing 6.2 shows the JobPK primary key class.

Listing 6.2—JobPK Class Identifies a Job

  1: package data;
  2: 
  3: import java.io.*;
  4: import javax.ejb.*;
  5: 
  6: public class JobPK implements Serializable {
  7:   public String ref;
  8:   public String customer;
  9: 
 10:   public JobPK() {
 11:   }
 12:   public JobPK(String ref, String customer) {
 13:     this.ref = ref;
 14:     this.customer = customer;
 15:   }
 16: 
 17:   public String getRef() {
 18:     return ref;
 19:   }
 20:   public String getCustomer() {
 21:     return customer;
 22:   }
 23: 
 24:   public boolean equals(Object obj) {
 25:     if (obj instanceof JobPK) {
 26:       JobPK pk = (JobPK)obj;
 27:       return (pk.ref.equals(ref) && pk.customer.equals(customer));
 28:     }
 29:     return false;
 30:   }
 31:   public int hashCode() {
 32:     return (ref.hashCode() ^ customer.hashCode());
 33:   }
 34:   public String toString() {
 35:     return "JobPK: ref=\"" + ref + "\", customer=\"" + customer + "\"";
 36:   }
 37: }

Note that the ref and customer fields have public visibility. This is a requirement of the EJB specification. Each field must correspond—in name and type—to one of the fields of the bean itself. This might seem like a strange requirement, but is needed by the EJB container to manage CMP beans.

To implement the equals() method, test that all fields of the object have the same value as the fields in the provided object. For primitive values, the regular == operator should be used, but for object references, the equals() method must be called.

To implement the hashCode() method, generate an int value that is based entirely and deterministically on the value of the fields, such that

if A.equals(B) == true then A.hashCode() == B.hashCode().

There are a couple of ways to accomplish this. A quick way to do this is to convert all the values of the primary key class' fields to Strings, concatenate them to a single String, and then invoke the hashCode() on this resultant string. Alternatively, the hashCode() values for all of the fields could be or'd together using the ^ operator. At runtime, this will execute more quickly than the concatenation approach, but it does mean that the distribution of hashcodes may be less good for primary keys with many fields. This is the approach used in Listing 6.2.

NOTE

Creating these primary key classes can be somewhat tedious. But remember that if there is a single (non-primitive) field in the bean that identifies that bean, this can be used instead.

Failing that, a single primary key class can be used for multiple beans. For example, you could create a IntPK class that just encapsulates an int primitive value.

Home Methods

In addition to finder, create, and remove methods, it is also possible to define home methods within the local-home interface. These are arbitrary methods that are expected to perform some business-type functionality related to the set of beans. In other words, they are an EJB equivalent of Java class methods (defined with the static keyword).

Some common uses for home methods include defining a batch operation to be performed on all bean instances (such as decreasing the price of all catalogue items for a sale), or various utility methods, such as formatting a bean's state for a toString() method.

NOTE

One question that sometimes arises is whether all database updates should be performed through Entity bean methods. One example given for a home method of a bean would be to decrease the price of all catalogue items for a sale. Iterating over perhaps 10,000 catalogue items and invoking setPrice( getPrice() * 0.9 ) is clearly going to cause massive amounts of SQL hitting the back-end RDBMS (or equivalent persistent data store).

In J2SE programs, a simple update, such as

UPDATE catalogue
set price = price * 0.9

is clearly the way to go. The ejbLoad() lifecycle method will ensure that any catalog item Entity bean will re-sync its state with the RDBMS.

Local Interface

Just as for Session beans with their remote interfaces, the local interface defines the capabilities of the Entity bean. Because first and foremost an Entity bean represents data, it is entirely to be expected that many of the methods exposed through the local interface will be simple getter and setter methods. Listing 6.3 shows the local interface for the Job bean.

Listing 6.3—JobLocal Interface

  1: package data;
  2: 
  3: import java.rmi.*;
  4: import javax.ejb.*;
  5: 
  6: public interface JobLocal extends EJBLocalObject
  7: {
  8:   String getRef();
  9:   String getCustomer();
 10:   CustomerLocal getCustomerObj(); // derived
 11: 
 12:   void setDescription(String description);
 13:   String getDescription();
 14: 
 15:   void setLocation(LocationLocal location);
 16:   LocationLocal getLocation();
 17: 
 18:   Collection getSkills();
 19:   void setSkills(Collection skills);
 20: }

Note that the setLocation() method accepts a LocationLocal reference rather than, say, a String containing the name of a location. In other words, the Job bean is defining its relationships to other beans, in this case the Location bean directly, effectively enforcing referential integrity. The client of the Job Entity bean is thus required to supply a valid location or none at all.

This is not to say that Entity beans cannot provide further processing. An example often quoted might be for a SavingsAccountBean. This might provide withdraw() and deposit() methods. The withdraw() method might well ensure that the balance can never go below zero. The bean might also provide an applyInterest() method, but it almost certainly would not provide a setBalance() method (if only!).

NOTE

Actually, such an SavingsAccountBean might well provide a setBalance() method, but would restrict access to administrators. You will learn more about security on Day 15, "Security."

Each of these methods has a corresponding method in the bean itself, and the exceptions list matches exactly. The implementation is shown in the "Implementing the Local-Interface Methods" section later today.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020