Introduction

OpenJPA is an open source implementation of the Java JPA (Java Persistence API) specification from Apache. JPA provides an agnostic Java-based API for storing and retrieving information to a backend database. It has a canonical query language named Java Persistence Query Language, or JPQL, that blends with the programming methods of Java and eliminates the need to tailor database queries for a particular database. However, JPA also supports native SQL which can be used for quick ports with a known backend database. This tutorial is designed to walk you through the steps of setting up a simple web application to use OpenJPA Geronimo and to transact the derby database that comes with Geronimo. The tutorial code uses a simple Java Server Page (JSP), backed up by some basic classes. It displays a table of inventory items and categories. In this tutorial, we will not dive into details regarding the JSP code. Its purpose is to be a window through which you can examine OpenJPA.  The intended audience for this tutorial is those with some knowledge and understanding of the Java programming language and who are just beginning with OpenJPA. To start, you must download the following requirements and install them on your computer. For the purposes of this tutorial, we are using Eclipse as the IDE and Microsoft Windows as the operating system of choice. 

Prerequisites

Geronimo V2.2: You can get it here. Download this file and unzip it to a permanent location. There is no installer. The server will run from the command line.

Java (J2SE) V1.6: This tutorial was developed and tested with Java V1.6. If you don't already have Java V1.6 you can get the IBM JDK here or the Sun JDK here.

Eclipse V3.2 or later: This version has annotation support included. Annotations play a large role in OpenJPA.  DownloadEclipse 3.2 or later.

Apache OpenJPA library: For the purpose of implementing this tutorial you can select
OpenJPA v1.2 or greater. You can download Apache OpenJPA from the Apache site. Note that the Milestone (openjpa-all-2.0.0-M3.jar as of this writing) is an early release of OpenJPA 2.0 and may have some instabilities. No issues have been noted for the usage in this tutorial.

The tutorial code files: These files are provided with this tutorial. You will add them to your Eclipse project.

Setup and Running the Sample

Now, that you have all the prerequisites for this tutorial downloaded and installed, the following sections will walk you through the Eclipse project setup and the OpenJPA configuration. Make sure you read through and follow each part carefully.  

Setting up Eclipse

After installing Eclipse, create a new project in a dedicated workspace for the tutorial. Complete the following setup instructions: First, make sure your Eclipse environment is updated and has the Geronimo plugin. If you do not know how to do that, follow the instructions found at the Geronimo website.

  1. Create a new Java project in Eclipse called, "OpenJPATutorial".
  2. Under the Target Runtime section, select Apache Geronimo v2.2.
  3. Now, click the Next button. You should see this:



  4. Now, your Project Explorer should look like this (partially expanded):



  5. Now we will bring in the sample code. The easiest way to add the sample code is to find the source provided with this tutorial and copy it to the src folder under the OpenJPATutorialWeb folder in your project directory in Windows Explorer:



  6. Now copy the index.jsp file from the tutorial into the Web Content directory under the Project directory in Windows Explorer:



Running and Configuring Geronimo and Derby

Geronimo has no installer and runs from the command line. Here are some quick instructions to get you started.

  1. In Windows, open a command prompt and navigate to the Geronimo bin directory.
  2. Type the command:
    start-server
    




    Press the Enter key.



  3. Open a web browser and go to the address:

    http://localhost:8080/console





    The default password is manager.

  4. You will come to the Welcome page. On the left menu, at the bottom, find the section for the Embedded DB. This is the Derby database control page.




  5. Click on the link for the DB Manager.
  6. You will see two sections: DB Viewer and Run SQL.
  7. In the Run SQL section, in the text field labeled Create DB, type in StoreSystem. This is the name of the database that the OpenJPA sample is configured to transact.




  8. Click on the Create button. You should now see the StoreSystem database appear in theDB Viewer section.




  9. We are now ready to deploy and run the sample code.


Running and Deploying the Sample Code in Geronimo

The sample code provided with this tutorial is working code. It is a simple inventory database program that shows items and categories. But even this simple example requires the ability to add, edit and delete entries. It requires the ability to sort and filter database queries and it requires the identification of the relationship of the items to the categories. In this example, the relationship is one to many. Knowing that relationship is important to how the code is written. Before we analyze the code and OpenJPA, we will first deploy the sample and see it work. To deploy the sample code follow these instructions:

  1. In Eclipse, in the Project Explorer, right click on the OpenJPATutorial project and select: Export->EAR file.




  2. In the Ear Export dialog, find a convenient place to put the exported EAR file.
  3. Check the Overwrite existing file check box.




  4. Click Finish.
  5. Go out to Windows Explorer and copy the file TutorialDeploymentPlan.xml to the location of the exported ear. This is the deployment plan that Geronimo requires to deploy the application.




  6. Open the Geronimo console in a web browser and log in.
  7. In the Console Navigation menu on the left, under the Applications section, click on the Deploy New item.
  8. Browse to the location of the exported EAR file and the deployment plan XML file.




  9. Click on the Install button. You should see this.




  10. In the Console Navigation menu on the left, under the Applications section, click on the Web App WARs item.
  11. Click on the link OpenJPATutorial and now you should see this:




    Each of the buttons will execute OpenJPA code. The lists are filled by running queries on the Derby database.
    1. Add a some categories and items
    2. Make sure you test each of the buttons and see the results.

Examining the Sample Code

Now that everything is set up and you have seen it work, let's look more closely at the parts of the code that use OpenJPA. The JSP code is just a prop to explore OpenJPA and we will not examine it.The sample application source code is provided for this tutorial and you may run as-is with no customizations. However, you have the option of reproducing the code manually using the following explanations. Whichever method you choose, locate the code that corresponds to explanations as you follow along.

package tutorial;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Version;

@Entity
public class InventoryCategory
{
   private int version;
   private int id;

   private String categoryName;
   private String categoryDescription;

   List<InventoryItem> items;

   public InventoryCategory(){}

   @Column(name = "categoryName")
   public String getCategoryName()
   {
      return categoryName;
   }

   public void setCategoryName(String name)
   {
      this.categoryName = name;
   }

   @Column(name = "itemDescription")
   public String getCategoryDescription()
   {
      return categoryDescription;
   }

   public void setCategoryDescription(String description)
   {
      this.categoryDescription = description;
   }

   @Version
   @Column(name = "version_field")
   // not required
   public int getVersion()
   {
       return version;
   }

   public void setVersion(int version)
   {
      this.version = version;
   }

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   public int getId()
   {
      return id;
   }

   public void setId(int id)
   {
      this.id = id;
   }

   @OneToMany(targetEntity=tutorial.InventoryItem.class,
      cascade=CascadeType.ALL,
      mappedBy="category")
   public List<InventoryItem> getItems()
   {
      return items;
   }

   public void setItems(List<InventoryItem> items)
   {
      this.items = items;
   }

   public void addItem(InventoryItem item)
   {
      this.items.add(item);
   }
}


In this example, the property annotations ( @Column,@Version, and @Id) are placed on the getter methods. They can alternatively be placed on the property declarations. For more information on these annotations and to see what other annotations are in OpenJPA, see the Apache OpenJPA 2.0 User's Guide: Chapter 5

  • The annotated class and property declarations are all that are required.
  • The @Id annotation is needed as the unique identifier (primary key) for each record.
  • The @Version annotation is common practice. It ensures data integrity during merges and acts as an optimistic concurrency control.
  • Every property must have both a getter and a setter and the standard case convention must be observed.
              °  Correct: public void setCategoryName(String name)
              °  Incorrect: public void setcategoryname(String name)


Summary

This was a very basic example of how to use OpenJPA with Geronimo and Derby. However, many applications that require database persistence do not use much more than the basic functionality demonstrated in this tutorial. The purpose of this was to be a primer. Aside from the setup of the server and database, we went through the creation of a persistence.xml file, the basics of the OpenJPA Entity, and EntityManager and some of the functionality.
Exercises
Using this sample code as a base, try to do some of the following:

*To make these changes you may have to delete the existing database tables so that they can recreated with the new relationship fields.


References