Leveraging OpenJPA with WebSphere Application Server V6.1

Updated for JPA 2.0

The Apache OpenJPA project is an open-source implementation of the Java™ Persistence API, focused on building a robust, high performance, scalable implementation of the JPA specifications. This article introduces OpenJPA with a complete example of how to take advantage of some of these features using IBM® WebSphere® Application Server V6.1. Updated for JPA 2.0. This content is part of the IBM WebSphere Developer Technical Journal.

Roland Barcia, Senior Technical Staff Member, IBM

Kevin Sutter, Senior Software Engineer, IBM

Author photoKevin Sutter is a Senior Software Engineer in the WebSphere Application Server development group. He is currently the lead architect for the Java Persistence API solution for WebSphere Application Server. Kevin is also a committer and a member of the PMC for the Apache OpenJPA project. Kevin's past roles include leading and architecting the WebSphere solutions for J2EE Connector Architecture (JCA) and WebSphere eXtremeScale (caching framework).



30 March 2011 (First published 06 December 2006)

Also available in Chinese Japanese

Introduction

The EJB 3.0 specifications provide a major (some say necessary) overhaul of the EJB programming model. Focused on the use of annotated POJOs (plain old Java objects), the whole EJB programming model is radically different from past EJB specifications. One aspect of this new programming model that is getting a lot of attention is the persistence architecture. This article introduces this new Java Persistence API with a complete example of how to take advantage of some of these features now, using WebSphere Application Server V6.1.

This article focuses on the use of OpenJPA on WebSphere Application Server V6.1 without the EJB 3.0 feature pack. The EJB 3.0 Feature Pack has not been updated to support the JPA 2.0 specification, but if you find the JPA integration limitations that are described in this article acceptable, then using OpenJPA 2.x with WebSphere Application Server V6.1 is possible.

This article was updated based on these software levels:

  • WebSphere Application Server V6.1.0.35
  • Application Server Toolkit V6.1.1.9
  • Apache OpenJPA V2.0.1

A brief overview of JPA

The Java Persistence API 1.0 (JPA) was a member of the Java EE 5 EJB 3.0 (EJB 3) family of specifications. The EJB 3 expert group produced three specifications:

  • EJB Core Contracts and Requirements
  • EJB 3.0 Simplified API
  • Java Persistence API 1.0.

In July 2007, JPA 2.0 was proposed as its own specification, JSR-317. It remains a member of the Java EE 6 family of specifications, but it is no longer tied to the EJB specification.

The JPA specification defines the management of persistence and object/relational mapping with both the Java EE and Java SE environments.

In a nutshell, the JPA specification covers the following key areas:

  • A new POJO-based programming model is introduced, which applies equally well to both the Java EE and Java SE environments. Annotations can now be used to define metadata directly in the application code, in addition to having an XML-based mechanism. Also, the entity POJOs no longer need to implement any EJB framework-based interfaces.

    • The programming model also defines a detachment model for the POJO (Entity) objects. This should be a benefit to the client/server and Web application environments.
    • Besides enhancing the EJB Query Language (also known as JPQL), the programming model also enables the use of native SQL queries.
  • The JPA specification also explicitly defines the object/relational (O/R) mapping instead of relying on vendor-specific O/R mapping of past releases. This should help with vendor plugability and application migration.

  • A few other items related to persistence were also standardized:

    • Object versioning for optimistic concurrency control
    • Database key generation
    • Lazy vs. eager loading of fields
    • Inheritance.
  • JPA 2.0 introduced:

    • Additional O/R Mapping enhancements for a more complete solution.
    • A standardardized pessimistic lock manager.
    • Access to a JPA provider’s L2 cache, if available.
    • A programming interface to query capabilities via the Metamodel and Criteria APIs.
    • Integration with Bean Validation (JSR 303).

All this simplification does come with a slight cost. Due to the major shift in the programming model, existing EJB 2.x applications will need to be rewritten to take advantage of the new JPA features. Also, the new JPA specification does not include automatic container-managed relationship (CMR) maintenance. Relationship maintenance is now application-managed.

Additional detail on the Java Persistence API can be found on the Java Community Process Web site, as well as in several whitepapers, articles, presentations, and books (see Resources).


Introduction to OpenJPA

The Apache OpenJPA project is an Apache-licensed open-source implementation of the Java Persistence API. OpenJPA is focused on building a robust, high performance, scalable implementation of the JPA specification.

Because of the industry interest in this OpenJPA project, this article will help explain how to take immediate advantage of this implementation in your WebSphere Application Server environments.

This article applies equally well to both JPA 1.0 and JPA 2.0 standards. The concepts, samples, explanations, and the screen captures will apply regardless of the specific OpenJPA release that you use.


A look at the sample application

For our example, we are using a Customer Order System, in which a customer creates an order, adds line items, and then submits the order. Figure 1 illustrates the use cases in our sample system.

Figure 1. Sample application use cases
Figure 1. Sample application use cases

The activity diagram in Figure 2 illustrates the sequence in which the use cases are executed.

Figure 2. Sample application use case sequence
Figure 2. Sample application use case sequence

In this example, we are only focused on the Persistence layer, since our goal is to show how you can use OpenJPA as your persistence layer in WebSphere Application Server V6.1.

Figure 3. Database data model
Figure 3. Database data model

In our sample database, there are four tables:

  • CUSTOMER:
  • ORDER:
  • LINEITEM:
  • PRODUCT:

In our sample application, we have four corresponding JPA entities, as shown in the class diagram in Figure 4.

Figure 4. Class diagram
Figure 4. Class diagram

A couple of interesting points to note about the mapping:

  • Customer Entity has a one way one-to-one relationship to CustomerOrder, while Order has a one-way many-to-one relationship back to Customer. The reason why this is not a two-way relationship is that Customer only maintains an instance of the current open order. The Order Table, however, has all the orders for the customer, no matter what the state of the order is. Because we have one-way relationships, this affects the way you set up the relationships, since each side has to be set.

  • CustomerOrder and Line Item has a bi-direction, and therefore, managed relationship.

We use an EJB session facade layer to represent the use cases. Because WebSphere Application Server V6.1 supports EJB 2.1, we use EJB 2.1 session beans. However, realizing the coming support for EJB 3, we moved all of the facade logic into a POJO. This way, when you move to EJB 3 session beans, all you have to do is remove the EJB 2.1 session bean layer, and annotate the POJO. Figure 5 is the class diagram for the session bean and the corresponding POJO.

Figure 5. Class diagram for session bean and POJO
Figure 5. Class diagram for session bean and POJO

To illustrate the flow, the sequence diagram illustrates the implementation of the Find Customer use case. All the facade logic is done in the OrderProcessor POJO. The Order Processor interacts with the JPA entity manager and the JPA POJOs to accomplish its persistence code. The EJB 2.1 session bean delegates to the POJO. You can examine the code later.

Figure 6. Sequence diagram
Figure 6. Sequence diagram

Similarly, the Open Order implementation is shown in Figure 7. All of the use cases follow this basic flow of EJB 2.1 session bean, calling a facade POJO, which in turn interacts with the JPA entity manager.

Figure 7. Open Order implementation
Figure 7. Open Order implementation

Setting up the JPA development environment with the Application Server Toolkit

To run this example, you will need to download the materials that accompany this article.

Access OpenJPA build

Since the usage of OpenJPA in this article is for an application-managed persistence environment, you can use any of these OpenJPA releases:

  • OpenJPA v1.0.4 (latest release that corresponds to the WebSphere Application Server V6.1 Feature Pack for EJB 3.0)
  • OpenJPA v1.2.2 (latest release that corresponds to WebSphere Application Server V7.0)
  • OpenJPA v2.0.1 (latest release that corresponds to the WebSphere Application Server V7.0 Feature Pack for OSGi Applications and JPA 2.0)

You can access the OpenJPA 2.0.1 build by downloading the openjpa-0.9.6-incubating.zip file. For more details on other ways to download OpenJPA, see Resources.

You can unzip the download file anywhere. The root of the ZIP file contains the OpenJPA implementation JAR file, as shown in Figure 8.

Figure 8. OpenJPA implementation JAR file
Figure 8. OpenJPA implementation JAR file

(The OpenJPA 2.x releases introduced an "all" JAR file (ie. openjpa-all-2.0.1.jar) that contains all of the necessary dependencies in one, easy-to-use JAR file. However, to enable this article to be used with any OpenJPA release, the dependencies will be handled separately.)

Under the lib directory, you will find the needed dependencies.

Figure 9. JAR dependencies
Figure 9. JAR dependencies

We will show later how to package these JAR files in your EAR.

Set up workspace

WebSphere Application Server V6.1 ships with the Application Server Toolkit (AST) V6.1. The AST is a superset of the Eclipse Web Tools project, which adds WebSphere Application Server-specific functionality, such as a WebSphere Application Server test server. In this section, you will see how to set up your AST for seamless OpenJPA development.

  1. Start the Application Server Toolkit:

    1. Open an empty workspace.

      Figure 10. Launch workspace
      Figure 10. Launch workspace
    2. Close the Welcome screen.

      Figure 11. AST Welcome
      Figure 11. AST Welcome
    3. Switch to the J2EE perspective.

      Figure 12. Select J2EE perspective
      Figure 12. Select J2EE perspective
  2. The first thing you have to do is to setup WebSphere Application Server V6.1 as a unit test environment. We are assuming you have a local single server WebSphere Application Server V6.1 installation already in place. We also assume that you have created a profile. (See Resources for more information on installation and profiles.)

    1. Go to the Servers view and right click within the view.

    2. Select New => Server (Figure 13).

      Figure 13. Create new server
      Figure 13. Create new server
    3. Select IBM=>WebSphere v6.1 Server and Create New runtime, then press Next (Figure 14).

      Figure 14. Create new runtime
      Figure 14. Create new runtime
    4. Keep the default value for Name, and point to the installation directory of WebSphere Application Server V6.1. Press Next.

      Figure 15. Define new runtime
      Figure 15. Define new runtime
    5. Select an application server profile with the appropriate SOAP port numbers. In our example, we used a non-secured profile. Press Finish.

      Figure 16. Define new server
      Figure 16. Define new server
  3. Your AST may be set up to use a Java 1.4 JDK and JRE by default. You need to update the preferences so you can compile Java 5 code, since JPA relies on Java 5 annotations and features.

    1. Select Window from the main menu, and then Preferences.

      Figure 17. Change preferences
      Figure 17. Change preferences
    2. Expand the Java section and select Compiler.

    3. Switch the Compiler compliance level to 5.0, then Apply.

      Figure 18. Change compiler compliance level
      Figure 18. Change compiler compliance level
    4. Switch to the Installed JREs and select the WebSphere Application Server v6.1 JRE.

      Figure 19. Switch JRE
      Figure 19. Switch JRE
    5. Press OK to save the changes and then Yes to do a build.

      Figure 20. Change compiler settings and build
      Figure 20. Change compiler settings and build

Create a Java EE project

In this section we will walk through creating the various Java EE projects and setup the EAR file to contain JPA.

  1. To create an Enterprise Application Project and its corresponding sub-projects (an EJB project and Web project), right-click Enterprise Applications in the Project Explorer and select New => Enterprise Application Project.

    Figure 21. Create Enterprise Application Project
    Figure 21. Create Enterprise Application Project
  2. For Project Name, enter OpenJPATestEAR, and for the Target runtime, select WebSphere Application Server v6.1 (Figure 22). Be careful that you do not accidentally select WebSphere Application Server v6.1 stub. Leave Configurations as <custom>. Press Next.

    Figure 22. Define Enterprise Application Project
    Figure 22. Define Enterprise Application Project
  3. Accepts the defaults on the Select Project Facets page and press Next (Figure 23).

    Figure 23. Select Project Facets
    Figure 23. Select Project Facets
  4. On the J2EE Modules to Add to EAR panel, ensure that Content Directory is set to EarContent. Press New Module... to start the New J2EE Module wizard (Figure 24).

    Figure 24. Start New J2EE Module wizard
    Figure 24. Start New J2EE Module wizard
  5. Create an EJB project and a Web project with these names (Figure 25):

    • EJB module: OpenJPATest
    • Web module: OpenJPATestWeb

    Press Finish.

    Figure 25. Create default J2EE modules
    Figure 25. Create default J2EE modules
  6. The modules you just created will be listed in the project window. Press Finish to complete the creation of the EAR project (Figure 26).

    Figure 26. EAR project creation completed
    Figure 26. EAR project creation completed

Be aware that you will have some compile errors until all the necessary artifacts are created and the required dependencies are imported.

Set up DB2 database and WebSphere Application Server database configuration

To run the application, you must set up the database. In our example, we used DB2® Version 9, and provided both a table DDL script and test data. Depending on the database you use, you may need to modify the schema. (Alternatively, you can use the OpenJPA documentation to generate a DDL for your database. See Resources for more information.)

  1. Find the scripts you will need in the OrderEntryDB folder of the provided download file.

  2. Use a DB2 command window to run these scripts. To access a DB2 command window, navigate to IBM DB2 => Command Line Tools => Command Window.

    1. Create a DB2 database by entering a DB2 command like this:

      db2 create db JPATEST

    2. When the database is created, connect to the database from the same command window with a command like this:

      db2 connect to JPATEST user db2admin using db2admin

    3. Run the DDL script included in the download file by issuing this command:

      db2 –tvf C:\<directory>\createTables.DDL

    4. You can run the data creation scripts in a similar fashion:

      db2 –tvf C:\<directory>\createData.sql

  3. To simplify this example, we used a feature in WebSphere Application Server called an enhanced EAR. This feature lets you store the database configuration in the application. Upon application install, WebSphere Application Server will use this information to create the appropriate configuration. This will save time when configuring the JDBC driver and DataSource needed by the application server.

    (Keep in mind that the enhanced EAR feature is used for rapid-prototyping, but it is a best practice to configure the required resources on the server using wsadmin scripts (or the administrative console) so that applications can be properly administered in various test environments and production.)

    1. To add the database configuration to the application, open the application.xml file in the EAR project. You can do this by double clicking the OpenJPATestEAR deployment descriptor icon, shown in Figure 27.

      Figure 27. Open EAR project
      Figure 27. Open EAR project
    2. Select the Deployment tab. Figure 28 highlights the configuration items of interest.

      Figure 28. Deployment descriptor configuration
      Figure 28. Deployment descriptor configuration

      Click to see larger image

      Figure 28. Deployment descriptor configuration

      Figure 28. Deployment descriptor configuration
    3. As you can see, there are various sections within the configuration panel. To enter values, press Add to launch a wizard for a specific configuration item. Below is a summary of the values you will enter or select for each section. When you have completed this configuration panel, remember to save the Application Deployment descriptor.

      JDBC Driver used:

      • Screen 1:
        • Database type: IBM DB2
        • JDBC provider type: DB2 Universal JDBC Provider (XA)
          (Make sure you use the type 4 Universal Driver which uses the needed JDBC 3.0 API's).
      • Screen 2:
        • Name: DB2XA
        • Implementation class name: com.ibm.db2.jcc.DB2XADataSource
        • Accept default Class path and Native path

      DataSource used:

      • Screen 1:
        • Provider Type: DB2 Universal JDBC Driver Provider (XA)
        • Version 5.0 data source
      • Screen 2:
        • Name: OrderDS
        • JNDI Name: jdbc/orderds
        • Container-managed authentication alias: DBUser
      • Screen 3:
        • Database Name: JPATEST
        • Server Name: localhost

      Authentication Alias:

      • Alias: DBUser
      • User id: <<database id>>
      • Password: <<password>>

      Substitution Variables:

      • DB2UNIVERSAL_JDBC_DRIVER_PATH: <<DB2 Root>>/java
      • Example: C:\Progra~1\IBM\SQLLIB\java

Add JPA JAR files to your enterprise application

You need to add the OpenJPA JAR and dependencies to the EAR file by importing them into the EarContent file of the Enterprise Application Project:

  1. First, add the dependent JAR files:

    1. Right click the EarContent folder under the OpenJPATestEAR project and select Import... as shown below.

      Figure 29. Import JAR files
      Figure 29. Import JAR files
    2. Select File system, then Next (Figure 30).

      Figure 30. Select file system
      Figure 30. Select file system
    3. In the From directory field, navigate to the directory where you downloaded JPA, and then to the lib directory within that. Select the following JAR files (Figure 31):

      • common-collections-3.2.1.jar
      • common-lang-2.1.jar
      • commons-pool-1.5.3.jar
      • geronimo-jpa_2.0_spec-1.1.jar
      • serp-1.13.1.jar

      (Similar JAR files with slightly different release names need to be selected if you are using an alternate release of OpenJPA. The other dependency JAR files are not needed because WebSphere Application Server provides the J2EE JARs required, as well as common logging Also, since this example is using DB2, the Derby runtime JAR is not needed either.)

      Press Finish.

      Figure 31. Select JAR files to import
      Figure 31. Select JAR files to import
  2. Next we need to import the JPA implementation JAR file. Right click the EarContent folder under the OpenJPATestEAR project and select Import.... As before, point to the root of the JPA installation directory and select the following jar to import: openjpa-2.0.1.jar, then Finish.

    Figure 32. Import JPA implementation JAR file
    Figure 32. Import JPA implementation JAR file
  3. Next, update the EJB project classpath so that it will find the JAR files:

    1. Under the EJB Projects folder, right-click on the OpenJPATest project and select Properties (Figure 33).

      Figure 33. Open project properties
      Figure 33. Open project properties
    2. Change the output directory to be the same as the source directory. This will make sure the JPA Enhancement step works correctly. To do this, select the Java Build Path item and change the Default Output Folder to OpenJPATest/ejbModule (Figure 34).

      Figure 34. Make the output directory and source directory the same
      Figure 34. Make the output directory and source directory the same
    3. Switch to J2EE Module Dependencies and select all the JARs, as shown in Figure 35.

      Figure 35. Select all dependent JAR files
      Figure 35. Select all dependent JAR files
  4. Now you can import the Java source for your project.

    1. Right click the ejbModule folder under the OpenJPATest Project and select Import.

    2. Select File system and then Next.

    3. Assuming you have expanded the download materials into a directory, enter the ejbModule folder under the download directory (Figure 36).

      Figure 36. Import downloaded resources
      Figure 36. Import downloaded resources
    4. When asked for overwrite permission, select Yes To All.

Set up Eclipse build to include enhancement

OpenJPA relies on byte code enhancement to add persistence behavior to your JPA objects. There are several ways to enhance a class (see Resources). In our example, we have provided a simple ANT script that runs the enhancer. To make the development process simpler, you will incorporate the Ant build as part of the Eclipse build. This way, when you compile your classes in Eclipse, the JPA enhancer will run as part of the build. This will simplify your development process.

  1. The ANT script is a simple script that makes use of the OpenJPA enhancer tool. Open the build.xml file located in the root of the ejbModule directory. The ANT file points to the entity package as well as the persistence.xml file. (We will examine this file in the next section.)

    Figure 37. Open build.xml file
    Figure 37. Open build.xml file
    Listing 1
    <project name="enhanceJPA">
    <target name="enhance">
      <!-- define the openjpac task; this can be done at the top of the    -->
      <!-- build.xml file, so it will be available for all targets      -->
      <taskdef name="openjpac"
    classname="org.apache.openjpa.ant.PCEnhancerTask"/>
    
      <openjpac>
      	<config propertiesFile="./META-INF/persistence.xml"/>
        <fileset dir=".">
        <include name="**/com/ibm/persistence/ejb3/order/entity/*.java" />
        </fileset>
        <classpath>
          <pathelement location=”${basedir}” />
        </classpath>
      </openjpac>
    </target>
    
    </project>
  2. To run the enhancer as part of the Eclipse build, you need to configure a builder:

    1. Right click the OpenJPATest EJB project and select Properties.

      Figure 38. Open project properties
      Figure 38. Open project properties
    2. In the Builders section, press New and select Ant Build (Figure 39).

      Figure 39. Configure Ant build
      Figure 39. Configure Ant build
    3. Name the builder JPAEnhance.

    4. Under the Main tab, browse the workspace and select the build.xml file under the ejbModule directory.

    5. In the Base Directory section, browse the workspace and select the ejbModule directory.

    6. In the Arguments section, add the "-verbose -debug" flags. The final configuration should look like Figure 40.

      Figure 40. Configure builder
      Figure 40. Configure builder
    7. Under the Refresh tab select Refresh resources upon completion to refresh the entire workspace once the enhancement is done (Figure 41).

      Figure 41. Refresh workspace upon completion
      Figure 41. Refresh workspace upon completion
    8. Switch to the Targets tab and select the enhance tasks in Clean, Manual Build and Auto Build (Figure 42).

      Figure 42. Select enhance tasks
      Figure 42. Select enhance tasks
    9. Under the Classpath tab (Figure 43), add all the JPA JARs by pressing Add Jar and adding all EAR content by browsing the workspace and selecting the EAR file.

    10. Finally, add the j2ee.jar file that is in the lib directory of your WebSphere Application Server install. Do this by adding selecting Add external JARs....

      Figure 43. Add JAR files to the configuration
      Figure 43. Add JAR files to the configuration
    11. Press OK to save the builder.

    12. The JPAEnhance task should be the last thing to happen in your build (Figure 44). If you have automatic build, your enhancer should run (Figure 45). Figure 46 shows an example of output from a successful enhancement run.

      Figure 44. Build tasks
      Figure 44. Build tasks
      Figure 45. Activate automatic build
      Figure 45. Activate automatic build
      Figure 46. Output from a successful enhancement run
      Figure 46. Output from a successful enhancement run

Examine the sample application

Now that we have configured our database, server configuration, and workspace, let's examine the application. We have already provided an overview of the architecture, so we will just highlight the packaging and look at the OpenJPA configuration.

  1. Using the Project Explorer, expand the ejbModule folder to see all the packages. Figure 47 summarizes the location of the packages.

    1. The JPA entities package contains the annotated JPA entity objects.

      Figure 47. All ejbModule packages
      Figure 47. All ejbModule packages
    2. Examine the entities. Listing 2 shows the Customer Entity object. You can make it persistence-enabled by adding the annotations, as shown in the class below.

      Listing 2
      package com.ibm.persistence.ejb3.order.entity;
      
      import java.io.Serializable;
      import javax.persistence.*;
      
      @Entity
      @Table(name="CUSTOMER", schema="CUSTSCH")
      public class Customer implements Serializable {
      
      	
      	private Integer id;
      	private String name;
      	private CustomerOrder currentOrder;
      		
      	@Id
      	@Column(name="CUST_ID")
      	public Integer getId() {
      		return id;
      	}
      	public void setId(Integer id) {
      		this.id = id;
      	}
      	
      	@Column(name="NAME")
      	public String getName() {
      		return name;
      	}
      	public void setName(String name) {
      		this.name = name;
      	}
      	
      	
      	 @OneToOne(fetch=FetchType.EAGER,cascade = 
      {CascadeType.MERGE,CascadeType.REFRESH},optional=true )
      	 @JoinColumn(name="OPEN_ORDER_ID",referencedColumnName="
      ORDER_ID") 
      	public CustomerOrder getCurrentOrder() {
      		return currentOrder;
      	}
      	public void setCurrentOrder(CustomerOrder currentOrder) {
      		this.currentOrder = currentOrder;
      	}
      
      }
    3. In addition, you can see the POJO facade package containing the OrderProcessorBean. The package uses the JPA to access and update entities. Listing 3 shows a portion of the OrderProcessorBean. Notice that in the constructor we look for two EntityManagerFactories. We will see why in the next section.

      Listing 3
      public class OrderProcessorBean implements OrderProcessor {
      
      	private EntityManagerFactory emf;
      	
      	private EntityManagerFactory emfPessLock;
      	
      	public OrderProcessorBean() {
      		emf = 
      EntityManagerFactoryHelper.getEntityManagerFactory("OrderDB");
      		emfPessLock = 
      EntityManagerFactoryHelper.getEntityManagerFactory("OrderDBPessLock");
      	}
      
      	public Customer findCustomerById(int customerId) throws 
      CustomerDoesNotExist{
      		//1. Finds customers by ID.
          EntityManager em = null;
          try {  
      	em = emf.createEntityManager();
      	Customer customer =   findCustomerByIdInternal(customerId,em);
      	return customer;
          } finally {
            if (em != null) {
              em.close();
            }
          }
      }

      (We are using application-managed entity managers. This means we cannot inject the entity manager into calling code. Instead, we must load the EntityManagerFactory ourselves. In addition, you must be conscientious to close the EntityManager when you are done with it. We will elaborate on this in the next section.)

  2. The persistence.xml is the descriptor that defines the persistence unit which contains the needed configuration for the JPA entities and the database.

    1. Open the persistence.xml and examine the contents.

      Figure 48. Open persistence.xml
      Figure 48. Open persistence.xml
    2. Listing 4 shows persistence.xml. Notice there are two different persistence units. Previously, we mentioned that the OrderProcessor class used two EntityMangerFactories. Since we have both read and write access patterns, we need to define one for each type one for optimistic reads, the other for pessimistic updates. Several properties are defined:

      • JPA provider: in this case, OpenJPA.
      • jta-data-source: in this case, it is a resource reference defined on the calling session bean.
      • TransactionMode: managed; this enables OpenJPA to delegate transactions to the underlying EJB container.
      • ConnectionFactoryMode: managed; this enables the application server to manage connection access.
      • DBDictionary property: enables for proper translation to DB2 queries. If you are using another database, you need to adjust to the proper value (see the OpenJPA documentation in Resources for supported databases).
      • LockManager property: on the second persistent unit, this sets the lock to pessimistic enabling, for example, OpenJPA to use "select for update" when appropriate.
      • Log property: Commented out, but can be used to help debug potential OpenJPA usage issues.
      Listing 4
      <persistence 
      	xmlns="http://java.sun.com/xml/ns/persistence"
      	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      		http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
      	version="1.0">
      <persistence-unit name="OrderDB">
      	<provider>
      		org.apache.openjpa.persistence.PersistenceProviderImpl
      		</provider>
      		<jta-data-source>
      			java:comp/env/jdbc/orderds
      		</jta-data-source>
      		<properties>
      		<property name="openjpa.TransactionMode" 
      			value="managed"/>
      		<property name="openjpa.ConnectionFactoryMode" 
      			value="managed"/>
          		<property name="openjpa.jdbc.DBDictionary" 
      			value="db2"/>
                  <!-- <property name=”openjpa.Log”
                      value=”Default=TRACE”/>  -->
      	</properties>
      	</persistence-unit>
      	<persistence-unit name="OrderDBPessLock">
      	<provider>
      	org.apache.openjpa.persistence.PersistenceProviderImpl
      	</provider>
      	<jta-data-source>java:comp/env/jdbc/orderds</jta-data-source>
      	<properties>
      	<property name="openjpa.TransactionMode" 
      		value="managed"/>
      	<property name="openjpa.ConnectionFactoryMode" 
      		value="managed"/>
          	<property name="openjpa.jdbc.DBDictionary" 
      		value="db2"/>
      	<property name="openjpa.LockManager"
      		value="pessimistic(VersionCheckOnReadLock=true,VersionUpdate
      		OnWriteLock=true)"/>
                  <!-- <property name=”openjpa.Log”
                      value=”Default=TRACE”/>  -->
      	</properties>
      </persistence-unit>
      </persistence>

There are two EM configuration types:

  • JTA-configured type listens for transactional events (begin/commit/rollback) directly from the transaction service.
  • Resource-Local type learns about these events by the application calling the EntityTransaction interface.

Running Open JPA in WebSphere Application Server V6.1 enables the processing of JTA transactions through the above configuration. However, JPA defines the notion of container-managed entity manager versus application-managed entity manager. To understand the difference, you must first understand what a persistence context means.

A persistence context is a set of managed entity instances in which, for any persistent entity identity, there is a unique entity instance. Within the persistence context, the entity's association with the underlying persistence store is managed by the entity manager (EM).

A container-managed EM instance is created by directing the container to inject one instance (either through direct injection or through injection-like JNDI lookup); the lifetime of that EM instance is controlled by the container; the instance matches the lifetime of the component into which it was injected. For each container-managed EM instance, there are one or more corresponding container-managed persistence contexts (PC). At the time the PC is created, it is linked with the transaction currently in effect and propagated by the container, along with the transaction context to other called components within the same JVM. The container-managed usage scenario is further subcategorized into transaction-scoped (lifetime is controlled by the transaction) and extended (lifetime is controlled by one or more stateful session bean instances).

An application-managed EM instance is created by calling the EntityManagerFactory (which itself can be injected, or looked up in JNDI), and the lifetime of that instance is controlled by the application. For each application-managed EM instance, there are one or more corresponding application-managed persistence contexts, which are not linked with any transaction (isolated) and are not propagated to other components. This does not mean that application-managed entity managers cannot be configured as JTA entity managers. However, it is important to realize that you must open and close the entity manager yourself.

Both container-managed entity managers and application-managed entity managers (and their persistence contexts) are required to be supported in Java EE Version 5 Web containers and EJB containers. Within an EJB environment, container-managed entity managers are typically used. When using OpenJPA with WebSphere Application Server V6.1, only application-managed entity managers are usable. However, as stated, the application-managed entity manager can still be configured using JTA. Proper layering of your code should help one move to container-managed entity managers when moving to the EJB 3.0 feature pack or beyond.

Import the Web client

To test our application, we have provided a simple test servlet that executes our use cases in the desired sequence.

  1. First, you must import the Web artifacts:

    1. Right click the OpenJPATestWeb project and select Import (Figure 49).

      Figure 49. Import Web artifacts
      Figure 49. Import Web artifacts
    2. Select File System, then Next.

    3. In the From directory field, browse to the <<download materials>>/WebClient (Figure 50). Make sure the Into folder is the root of the Web project. Press Finish.

      Figure 50. Browse to the downloaded Web client
      Figure 50. Browse to the downloaded Web client
    4. Press Yes to All to override the default.

      Figure 51. Override default setting
      Figure 51. Override default setting
  2. Next, you need to update the Web project's classpath to point to the EJB JAR file.

    1. Right click the Web project and select Properties (Figure 52).

      Figure 52. Update project properties
      Figure 52. Update project properties
    2. Under the J2EE Module Dependencies, select the OpenJPATest.jar file and press OK (Figure 53).

      Figure 53. Select JAR file
      Figure 53. Select JAR file

Run application in WebSphere Application Server V6.1 through the Application Server Toolkit

Running the application just involves installing the EAR file and invoking the test servlet. You can do this in any of the supported deployment models of WebSphere Application Server. In our sample, we just test directly from the Application Server Toolkit.

  1. To install the application from the Application Server Toolkit, all you need to do is add the application to the server:

    1. In the Server view, right click the WebSphere v6.1 Server and select Add and Remove Projects... (Figure 54).

      Figure 54. Add project to server
      Figure 54. Add project to server
    2. Select the OpenJPATestEAR application from Available projects and select Add to move it to Configured projects (Figure 55). Press Finish.

      Figure 55. Move available projects to configured projects
      Figure 55. Move available projects to configured projects
    3. Monitor the console for both the starting server and the application (Figure 56). (If the server does not start, right click and press Start.)

      Figure 56. Console messages for application and server
      Figure 56. Console messages for application and server
  2. When the application has started, you can test the servlet:

    1. Expand OpenJPATestWeb => Servlets => JPATester. Right-click on JPATester, then select Run As => Run on Server (Figure 57).

      Figure 57. Test servlet
      Figure 57. Test servlet
    2. Check Set server as project default (Figure 58). (This only happens the first time you run a project.)

      Figure 58. Set project default
      Figure 58. Set project default
    3. The browser should open and display the results shown in Figure 59. The properly running servlet will display a customer without an order, open the order for a customer, add some line items, and then submit the order.

      Figure 59. Test results
      Figure 59. Test results

Conclusion

EJB 3 is a major update to the EJB specification that greatly simplifies EJB programming. The Java Persistence API (JPA) represents a major enhancement to persistence programming of the EJB 3 specification. Apache OpenJPA provides a great opportunity to begin using JPA on the WebSphere Application Server platform. By configuring and running the sample application, you saw how straightforward it can be to begin using JPA for new development projects today.


Acknowledgements

The authors would like to thank Randy Schnier, Jim Knutson, Jonathan Marshall, and Robert Peterson for their contributions to this article.


Download

DescriptionNameSize
Sample applicationOpenJPASample.kws.zip26 KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere, Open source, Java technology
ArticleID=182095
ArticleTitle=Leveraging OpenJPA with WebSphere Application Server V6.1
publish-date=03302011