Home > Articles > Web Development

This chapter is from the book

Development Process of the Common Example

Now that we have gone through OpenJPA in detail, we will show you the steps required to develop a complete application. To run it yourself, follow the directions in Appendix A, "Setting Up the Common Example." Keep in mind that Chapter 2, "High-Level Requirements and Persistence," and Chapter 3, "Designing Persistent Object Services," describe the requirements and design of our example. This section focuses on the details related to developing OpenJPA applications after you understand the requirements and settle on a design.

Defining the Object

When developing an OpenJPA application, you define your objects by coding Java Classes with annotations, and then coding XML mapping files. The following listings show our domain model implemented in Java with OpenJPA annotations being used to specify the mapping metadata. We only show subsets of the classes to illustrate the mapping. You can examine all the code by downloading the sample as shown in Appendix A. Listing 8.68 lists the AbstractCustomer superclass. It is mapped using a Single Table Strategy. Besides the defaulted primitive value fields, we explicitly map the open order field as a one-to-one relationship to the ORDERS table because a Customer object may have at most one open order, and we map the orders field as a one-to-many relationship with respect to the ORDERS table because a Customer might refer to more than one in any state, including open. The orders field is declared a bidirectional relationship, and therefore additional details are defined on the Order side. We also define an Eager fetching strategy, because we want to fetch the open order record whenever the customer is accessed. We use a Lazy option to load the orders collection only when we specifically access the history.

Listing 8.68. Abstract Customer

@Table(name = "CUSTOMER")
@DiscriminatorColumn(name="TYPE", discriminatorType = STRING)
public abstract class AbstractCustomer implements Serializable {

    protected int customerId;
    protected String name;
    protected String type;

        cascade = {CascadeType.MERGE,CascadeType.REFRESH},
    @JoinColumn(name="OPEN_ORDER", referencedColumnName = "ORDER_ID")
    protected Order openOrder;
    protected Set<Order> orders;

    ... //Gettters and Setters...

Listing 8.69 shows the ResidentialCustomer subclass. Notice we used the DiscriminatorValue to determine the type. We described this in the Inheritance section of the template.

Listing 8.69. Residential Customer

public class ResidentialCustomer
extends AbstractCustomer implements Serializable {
    protected short householdSize;
    protected boolean frequentCustomer;
    //Getters and Setters...

Listing 8.70 shows the BusinessCustomer subclass, which is similar to the ResidentialCustomer subclass.

Listing 8.70. Business Customer

public class BusinessCustomer extends AbstractCustomer implements Serializable {
    protected boolean volumeDiscount;
    protected boolean businessPartner;
    protected String description;
    //Getters and Setters...

Listing 8.71 shows the Order object. We elected to generate the Order ID using the Identity Strategy because this primary key is bound to a single table. We also map a relationship back to the AbstractCustomer using ManyToOne. The detail of this bidirectional relationship is defined on the Order object.

The Order object also has a Set of LineItems for the Order that implements a unidirectional relationship between the Order and LineItem classes. We have no requirement to navigate from a LineItem to an Order; defining a single-sided relationship will make the underlying SQL optimal.

Listing 8.71. Order Object

public class Order implements Serializable {
    protected int orderId;
    protected BigDecimal total;
    public static enum Status { OPEN, SUBMITTED, CLOSED }
    protected Status status;
        name="CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID"
    protected AbstractCustomer customer;

    @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.EAGER )
    protected Set<LineItem> lineitems;

    //getters and setters

Listing 8.72 shows the LineItem class. You will notice that the LineItem class is a composite key. This choice was made to illustrate how to map to certain legacy schemas. ORM technologies tend to work better with generated keys. The LineItem also has a one-to-one relationship to the Product. This is also a unidirectional relationship because there is no requirement to navigate from a Product instance to the LineItem objects that reference it. Product instances also usually are cached because the product catalog changes infrequently.

Listing 8.72. LineItem

    query="select l from LineItem l
           where l.productId = :productId and l.orderId = :orderId"

public class LineItem implements Serializable {
    private int orderId;

    private int productId;
    protected long quantity;
    protected BigDecimal amount;

    @ManyToOne(fetch = FetchType.EAGER)
            referencedColumnName = "PRODUCT_ID"
    protected Product product;

    //getters and setters

Listing 8.73 shows the composite primary key for the LineItem Entity.

Listing 8.73. Line Item ID

public class LineItemId implements Serializable{
    private int orderId;
    private int productId;
    //getters and setters
    public int hashCode() {
        //unique hashcode
    public boolean equals(Object obj) {

Listing 8.74 shows the Product. The Product is a simple class that is mapped to the PRODUCT table. It has no relationships. (Real products usually have many more details and belong to categories and such.) We have added a NamedQuery to the Product annotations to specify a query that retrieves the list of products. As noted previously, we also cache the Product. This example should not be considered complete and is for demonstration purposes only; products in real enterprise systems are usually indexed, categorized, and related to extensive catalog and inventory management systems.

Listing 8.74. Product

@NamedQuery(name="product.all",query="select p from Product p")
public class Product implements Serializable {
    protected int productId;
    protected BigDecimal price;
    protected String description;
    //getters and setters

We did not employ the option to provide XML mapping files. OpenJPA is meant to reduce the number of artifacts one has to develop. We could have chosen to minimize the annotations and specify the mapping inside XML descriptors. For example, in a real application, we recommend externalizing the cache period and the named query so that the code need not change to modify these parameters.

Implementing the Services

This section shows the implementation of the Service. For OpenJPA, we provided both an EJB 3 version of the service and a Java SE version. Because EJB 3 Session Beans are Java classes, the Java SE version just extends the proper EJB 3 class and bootstraps the EntityManager as described earlier. Figure 8.6 shows all the exceptions for our services. See the downloadable sample or refer to Chapter 3 for details.

Figure 8.6

Figure 8.6 Exceptions from the common example.

We have two implementations of our service: one for Java SE using OpenJPA and another using IBM JPA (built on OpenJPA) for EJB 3. The interface for the service was introduced in Chapter 3, so refer to the details there. For the EJB 3 version, the service interface has an extra @Local annotation to denote a Local EJB. The service implementations vary slightly from a bootstrapping standpoint with Java SE.

Specifically, the Java SE version of the application looks up the EntityManager using the EntityManagerFactory, as illustrated earlier in Figure 8.3. The EJB 3 version is illustrated earlier in Figure 8.5.

The loadCustomer operation uses the EntityManager find method to look up the customer. Because the mapping file defined the proper eager loading, it will load the customer record, an open order if it exists, and any line items for that order. The Inheritance is also automatic; based on the type, it will return the correct subclass. All this happens with one call. Listing 8.75 shows the loadCustomer method as implemented in the EJB 3 version. The Java SE version uses transaction demarcation. You can examine the downloadable source to see the difference. Appendix A shows how to load the code into your Eclipse-based development environment.

Listing 8.75. The loadCustomer Implementation

public AbstractCustomer loadCustomer(int customerId)
throws ExistException,GeneralPersistenceException {
    AbstractCustomer customer = em.find(
        AbstractCustomer.class, customerId
    return customer;

The openOrder operation creates an order Java Object and persists it. It then sets the new order onto the customer instance. The transaction is implied because of the nature of EJBs. The openOrder routine will check if an order is open and throw an exception if it is. Listing 8.76 shows the implementation.

Listing 8.76. The openOrder Implementation

public Order openOrder(int customerId)
throws CustomerDoesNotExistException, OrderAlreadyOpenException,
    AbstractCustomer customer = loadCustomer(customerId);
    Order existingOpenOrder = customer.getOpenOrder();
    if(existingOpenOrder != null) {
        throw new OrderAlreadyOpenException();
    Order newOrder = new Order();
    newOrder.setTotal(new BigDecimal(0));
    return newOrder;

The implementation for the addLineItem operation first checks to see whether the Product exists using the EntityManager find method as seen in the other examples. It then queries to check whether a Line Item already exists, and updates the quantity if it does. Otherwise, it creates a new instance. Again, the transaction is implied due to the EJB 3 method. Listing 8.77 shows the implementation of addLineItem.

Listing 8.77. The addLineItem Implementation

public LineItem addLineItem(
    int customerId,
    int productId,
    long quantity)
throws CustomerDoesNotExistException,
       InvalidQuantityException {
    Product product = em.find(Product.class,productId);
    if(quantity <= 0 ) throw new InvalidQuantityException();
    if(product == null) throw new ProductDoesNotExistException();
    AbstractCustomer customer = loadCustomer(customerId);
    Order existingOpenOrder = customer.getOpenOrder();
    if(existingOpenOrder == null) {
        throw new OrderNotOpenException();
    BigDecimal amount = product.getPrice().multiply(
        new BigDecimal(quantity)
    LineItemId lineItemId = new LineItemId();
    LineItem existingLineItem = em.find(LineItem.class,lineItemId);
    if(existingLineItem == null) {
        LineItem lineItem = new LineItem();
        return lineItem;
    else {
            existingLineItem.getQuantity() + quantity
        return existingLineItem;

The removeLineItem operation simply deletes the LineItem by finding the record and removing it. Listing 8.78 shows the implementation.

Listing 8.78. The removeLineItem Implementation

public void removeLineItem(
    int customerId,
    int productId
throws CustomerDoesNotExistException,
       GeneralPersistenceException {
    Product product = em.find(Product.class,productId);
    if(product == null) throw new ProductDoesNotExistException();
    AbstractCustomer customer = loadCustomer(customerId);
    Order existingOpenOrder = customer.getOpenOrder();
    if(existingOpenOrder == null ||
       existingOpenOrder.getStatus() != Order.Status.OPEN)
        throw new OrderNotOpenException();
    LineItemId lineItemId = new LineItemId();
    LineItem existingLineItem = em.find(LineItem.class,lineItemId);
    if(existingLineItem != null) {
    else {
        throw new NoLineItemsException();

The submitOrder operation is almost as simple—it changes the status of the order and removes it from the openOrder property of the abstract customer class. Listing 8.79 shows the submitOrder implementation.

Listing 8.79. The submitOrder Implementation

public void submit(int customerId)
throws CustomerDoesNotExistException, OrderNotOpenException,
       GeneralPersistenceException {
    AbstractCustomer customer = loadCustomer(customerId);
    Order existingOpenOrder = customer.getOpenOrder();
    if(existingOpenOrder == null ||
       existingOpenOrder.getStatus() != Order.Status.OPEN)
        throw new OrderNotOpenException();
    if(existingOpenOrder.getLineitems() == null ||
       existingOpenOrder.getLineitems().size() <= 0 )
        throw new NoLineItemsException();

Packaging the Components

The environment you deploy to will affect how the application is packaged. A Java SE environment may require you to copy files, or package the code into a JAR. You most likely have to write some deployment scripts. Figure 8.7 shows the Java Project in Eclipse. It is a plain Java Project with the persistence.xml defined in the meta-inf directory. The persistence.xml is necessary to obtain the connection.

Figure 8.7

Figure 8.7 Packaging.

In a Java EE application, you usually have to package an application in an EAR file. Figure 8.8 shows the layout of the EAR file, which is made up of other files, such as EJB-JAR files for EJBs or WAR files for web applications. See the Java EE specification for details. Notice that we can use the same Java SE JAR as an EJB 3 module as well.

Figure 8.8

Figure 8.8 Java EE EAR.

The persistence.xml file is packaged in the meta-inf directory and contains our persistence units. We illustrated the format earlier. As with the operation implementations, you can examine the downloadable source for more details.

Unit Testing

Depending on the methodology, you may have coded your unit test before or after implementing the service operations. Agile methods usually push a test-driven approach and encourage coding test cases first. Regardless, our OpenJPA example contains the unit test to run the application. Figure 8.9 shows the Unit Test project for the common example.

Figure 8.9

Figure 8.9 Unit Test package.

Chapter 3 explains the aspects of the unit test that are the same regardless of the persistence mechanism used (as it should be). The only difference with OpenJPA is that we also provide the option to look up the Session Bean in the Java EE case and use JUnitEE to run it. There is no JPA-specific information within the unit test, but there is EJB information. As long as you have the Java EE API JARs, this unit test can run in both a Java SE environment and a standard Java EE environment. Examine the downloadable source for details and Appendix A for instructions on how to run them.

Deploying to Production

Deploying to production involves setting the proper configuration values for the target environment. Other than the common testing needed to move an application to production, there are no additional considerations other than those already specified in this section. In a Java SE environment, you have to run the bytecode enhancer yourself. In a Java EE container, like WebSphere Application Server, the bytecode enhancer is run automatically when the installation tools are run, so it will not be an explicit step.

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