Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Advanced Container-Managed Persistence

Using the EJB 1.1 specifications, container managed persistence beans were not very powerful. In most cases, bean developers went quickly beyond the capabilities of CMP and had to convert to use bean managed persistence. Many developers shied away from using entity beans altogether. The EJB 2.0 quickly addressed many of these issues. This now allows the bean developer to implement most persistence requirements using container managed persistence. The four features that facilitate this are the following:

  • EJB query language

  • Finder methods

  • Relationship mapping of multiple entity beans

  • Business methods implemented within the home interface

The Enterprise JavaBeans Query Language

The Enterprise JavaBeans Query Language (EJB QL) specification defines a query language to be used within finder methods of an entity bean with container managed persistence. Rather than develop a completely new query language, the specification is based on a subset of SQL92. The EJB QL gives you the features to allow navigation over the relationships defined in an entity bean's abstract schema.

Your EJB QL queries will be contained within your deployment descriptor of the entity bean. The container will then translate these queries into the target language of the underlying data store. For example, EJB QL will be translated to true SQL for JDatastore. Using this translation allows entity beans using container managed persistence to be portable. In other words, the code is not tied to a specific type of data store or application server vendor.

EJB Query Restrictions

EJB QL has a few restrictions:

  • Commenting is not supported within EJB QL.

  • Date and time values are always represented in milliseconds and contained within a Java long.

  • Container managed persistence does not support inheritance. In other words, you cannot compare two entity beans of different types with each other.

Query Syntax

An EJB QL query has three components associated with it: SELECT, FROM, and WHERE. The SELECT and FROM clauses are the only required portions of EJB QL; the WHERE clause is optional. For example, SELECT OBJECT(e) FROM Employee e selects all the instances contained within the Employee entity.

The SELECT component defines the values or objects that will be returned by the created query. The return values can either be a local interface or a remote interface contained within an entity. The FROM component defines the scope of the query. It may declare one or more entities. Finally, the WHERE component contains a conditional expression that restricts the values retrieved by the query. As mentioned earlier, this portion of the query is optional; it is normally required to meet most entity finder requirements.

Examples Described


This method returns all the instances of employee contained within the entity. In this case, we refer to the Employee entity with an alias e to make the definition of the query shorter.


The query returns an employee instance specified by an empNo. This query is typically used to find an instance by either a primary key or alternate key. The DISTINCT keyword can be used to remove duplicates from the query but this should not happen if you are using a primary key.

SELECT DISTINCT OBJECT(e) FROM Employee e, IN (e.salaryHistory)
as s WHERE s.Country = ?1

This query navigates to related beans using the defined relationship. The e variable relates to the Employee entity bean, and the s variable represents the related bean instances SalaryHistory. The IN keyword specifies that SalaryHistory is a collection of beans related to the Employee entity. The query then navigates the relationship to identify all the salary histories within a specific country.


The employees whose salaries fall within a given range are returned. The BETWEEN keyword returns all salaries within the given range. This expression is useful when using range finder methods.

Expressions and Functions

Just like SQL92 specifications of which EJB QL specifications is a subset, EJB QL describes the functionality of the expressions and functions. The specification does not include a full list of functions like that of SQL92 but simply a subset that should fit most requirements (see Table 23.5).

Table 23.5 Expressions and Functions Contained Within EJB QL



Standard comparisons

Just like SQL, you have the operations =, >, >=, <, <=, and <>.


+, -, *, /




The BETWEEN expression determines whether a value falls within a range.


The IN expression determines whether a value is contained within a given set.


The LIKE expression evaluates whether a string matches a pattern. For a single character wildcard, use _. To use a wildcard that represents zero or more characters, use %.


The NULL comparison expression evaluates whether an attribute or set is null. This is not used to evaluate a null collection; we use the EMPTY expression to evaluate collections.

EJB QL also includes several functions, both arithmetic and string, listed in Table 23.6. Most EJB vendors, including Borland's Application Server, allow you to define and implement your own custom functions.

Table 23.6 Functional Expressions

Function Syntax


CONCAT(String, String)

Concatenate two strings together and return into a third.

SUBSTRING(String, start, length)

Return a substring based on the start and length passed in.

LOCATE(String, String [, start])

Locate a string within another and return its location.


Return the length of a string.


Return the absolute version of the number.


Return the square root of a number.

Finder Methods

The ability to find an entity is a key requirement of all entity beans. The implementation of finder methods, within EJB specification 1.1, required us to quickly move to bean managed persistence rather than use the simpler container managed persistence beans. Using EJB QL in conjunction with finder methods within a container managed persistent bean, you can meet most requirements for finding an individual or collection of entities.

We'll continue to look at our Employee entity and add a more complex finder other than findByPrimaryKey(). The requirement we need to implement is the capability to find employees based on a salary range. The following steps are required to build this finder method implementation:

  1. Right-click on the Employee entity and choose Add, Finder. The results of which display the finder editor.

  2. Add the finder properties required to accomplish the given task.

  3. Set the following properties (see Figure 23.6):

  4. Figure 23.6Figure 23.6 Finder editor within the EJB Designer.

    • Method name: findBySalaryRange

    • Return type: java.util.Collection

    • Input parameters: int low, int high

    • Home interface: local home

    • Query: SELECT OBJECT(e) FROM Employee e WHERE e.Salary BETWEEN ?1 AND ?2

  5. Save and compile your project.

The deployment descriptor now contains the information for this finder method (see Listing 23.18). When the bean is deployed to the container, it translates the information contained within the deployment descriptor EJB QL to standard SQL for JDatastore.

Listing 23.18 Portion of the Deployment Descriptor for Defining a Finder Method with EJB QL

 <ejb-ql>SELECT OBJECT(e) FROM Employee e WHERE e.Salary 
BETWEEN ?1 AND ?2</ejb-ql>

Relationship Mapping

As stated earlier the introduction of relationships in EJB 2.0 specifications makes a huge difference. These relationship mappings allow for not only providing the mechanics for managing relationships, but also the capability to model and implement complex business relationships with unidirectional and bidirectional traversal.

Each entity bean typically is not isolated in itself; it relates to other entities within our system. For example, the Employee entity we have been working with relates to many other entities within our system such as the salary history. To demonstrate relationships, we will start with one-to-many and move to more complex relationships, such as many-to-many.

One-to-Many Relationships

We can use a simple example for a one-to-many relationship. Using the sample database provided with JBuilder, each employee has a lengthy salary history that we want to make available through the instance (see Figure 23.7).

Figure 23.7Figure 23.7 Model of employee to salary history.

The process for creating this one-to-many relationship within JBuilder is accomplished by using the EJB Designer. The relationship ultimately is exposed via a local interface defined on the Employee entity bean. Ultimately, you would access this local interface by way of a session façade bean, but to make the example simple, we will use the remote interface with a test client.

  1. Expand the EmployeeData source and verify that the SALARY_HISTORY table is contained within the source's definition.

  2. Right-click on the SALARY_HISTORY table and select Create Entity Bean. The bean then appears in the EJB Designer. Make sure that the version property is set to EJB 2.0 compliant.

  3. Creating an EJB relationship is accomplished by right-clicking on the parent entity. In this class, right-click on our Employee entity and select Add, Relationship. An arrow used to graphically represent our relationship appears within the EJB Designer.

  4. Drag the end of the relationship arrow onto the SalaryHistory entity.

  5. Select the newly created method that contains the relationship. The name assigned by JBuilder's EJB Designer is salaryHistory.

  6. The Relationship Property editor appears to allow you to change the behavior of the relationship (see Figure 23.8).

  7. Figure 23.8Figure 23.8 Relationship Property editor for the Employee to SalaryHistory relationship.

  8. For the relationship properties, Multiplicity should be set to one-to-many, and Navigability should be set to unidirectional. The Navigability is set to unidirectional because it does not make sense to access Employee entity information through the SalaryHistory entity.

  9. Click on the Edit Table Reference button to open the Table Reference editor (see Figure 23.9). We will use this editor to provide the link/keys between the two entities.

  10. Figure 23.9Figure 23.9 Table Reference editor for the Employee to SalaryHistory relationship.

  11. Adding a relationship is important because it indicates all the important keys that define the relationship between parent and child entities. Double-click on the empNo in the Employee entity and drag it onto the empNo of the SalaryHistory entity. Click OK.

  12. You should have a new attribute that contains the relationship between the Employee and the employee's salary history. Using the property editor, shown in Figure 23.8, make sure that the return type of the salaryHistory method within the Employee entity is java.util.Collection.

Many-to-Many Relationships

A many-to-many relationship appears frequently in relationship database designs. It is usually implemented through the use of a resolution table because most relational database servers do not support this many-to-many relationship directly, although object modeling supports this relationship well. Although we can create this same resolution entity within our container, why not implement a many-to-many relationship that more accurately represents our actual instances?

For example, our employee system contains a many-to-many relationship implemented through a resolution table (see Figure 23.10).

Figure 23.10Figure 23.10 Employee relational data model.

Let's now create a many-to-many relationship using the existing employeeData source. The relationship will be exposed via local interfaces of the Employee and Project entity beans. To access these interfaces, we will use the local interfaces of the beans created. The following tasks help us create the required relationships and deployment descriptor for these entity beans:

  1. Right-click on the PROJECT table within the defined data module within the EJB Designer and select Create CMP 2.0 Entity Bean.

  2. Create the many-to-many relationship between the Employee and Project entity beans using the EJB Designer. This is accomplished by right-clicking on the Employee bean and selecting Add, Relationship; then drop the other end of the relationship on the Project entity.

  3. Select the newly created relationship entity called Project, and the relationship editor is created (see Figure 23.11):

  4. Figure 23.11Figure 23.11 Relationship editor for a many-to-many relationship.

    • Relationship name: employee-project

    • Multiplicity: many to many

    • Navigability: bidirectional

    • Field name: project

    • Return type: java.util.Collection

    • Getters/setters: local

  5. Click on Edit Table Reference; this launches the Table Reference editor.

  6. Click on Add Cross Table (see Figure 23.12). After you make the appropriate selections, the Add Cross Table button becomes available.

  7. Figure 23.12Figure 23.12 Table Reference editor to establish a many-to-many relationship.

  8. Select the EMPLOYEE_PROJECT table as the cross table (see Figure 23.13).

  9. Figure 23.13Figure 23.13 Table Reference editor to establish a many-to-many relationship using a cross table.


  11. Click OK and compile and save your project.

  12. Figure 23.14Figure 23.14 Build the relationship between the resolution table and the Employee and Project tables with the connected keys.

Home Business Methods

One of the new changes for the specification is the addition and support for collection methods and business methods contained within the home interface. For example, we might want to calculate the total current salary of all employees. The process for building this is simple:

  1. Add a new method to the Employee entity bean calling it calculateTotalSalary.

  2. Enter the return type to be a java.math.BigDecimal and the target interface should be local home.

  3. Create another finder method with the following parameters:

    • Finder name: findAll

    • Return type: java.util.Collection

    • Parameter: leave empty

    • Method interface: local home

    • Query: SELECT OBJECT(e) FROM Employee AS e

  4. Create a select method with the following properties:

    • Select name: selectAll

    • Return type: java.util.Collection

    • Parameter: leave empty

    • Result type mapping: local

    • Query: SELECT OBJECT(e) FROM Employee AS e

  5. Most of the code for the Employee entity has been generated by the EJB Wizard. The piece we need to add is the implementation of CalculateTotalSalary.

  6. Locate the EmployeeBean class and double-click to view the source.

  7. Locate the ejbHomeCalculateTotalSalary() method in the class.

  8. Implement the method as follows:

  9.  public java.math.BigDecimal  ejbHomeCalculateTotalSalary() {
      float res = 0;
      try {
       java.util.Iterator iter = ejbSelectAll().iterator();
        Employee emp = (Employee)iter.next();
        res = res + emp.getSalary().floatValue();
      catch (FinderException ex) {
       throw new javax.ejb.EJBException(ex);
      return new java.math.BigDecimal(new Float(res).toString());

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.


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.


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.


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.


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


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


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.


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.


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