Lab 7: Introduction to Java Persistence

In this lab, you will write a simple program that uses Java Persistence and entities.

Objectives:

Part 1: Database and Project Setup

In this part, you will configure the database for your lab. We will use the free, open-source H2 database, since it's easy to install run and administer. Note that the JPA code you will write is completely portable to other databases.

Steps:

  1. Ask your instructor for the following information:

    Lab Installation directory: ________________________________________

    TomEE Installation directory: ________________________________________

    If your computer has the standard lab setup on a computer running a version of Windows before Windows Vista, these directories will be:

    Lab Installation Directory:     c:\jeeclass
    TomEE Installation Directory:   c:\java\apache-tomee-plus-1.7.1
               

    If your computer is running Windows Vista, Windows 7 or later, the directories will be:

    Lab Installation directory:    c:\Users\username\jeeclass               
    TomEE Installation directory:  c:\Users\username\java\apache-tomee-plus-1.7.1               
                

  2. First, you need to make the H2 classes available to the TomEE server.

    In Eclipse, stop the TomEE server if it's running.

    Use Windows Explorer or My Computer to copy {Lab Installation Directory}/lib/h2/h2-1.3.161.jar to {TomEE Installation Directory}/lib.

  3. Next, you need to start the H2 database server and its administrative GUI, which is Web-based.

    Here are the instructions for Windows Vista or later. SKIP THIS IF YOUR COMPUTER HAS WINDOWS XP.

    1. The database server runs best in an Adminstrative command prompt. To open the command prompt, click the Windows Start menu and enter cmd into the Search box, to find cmd.exe, but don't press Enter.

      Right-click on cmd.exe and choose Run As Adminstrator to start the privileged command prompt.

    2. In the command prompt, change to {Lab Installation Directory}/lib/h2. If your computer has the standard lab setup, enter something like:

      cd \Users\username\jeeclass\lib\h2            
                  

      Note: You will need to substitute your actual user name.

    3. To start the H2 database server and admin GUI, enter:

      java -jar h2-1.3.161.jar            
                  

      The server runs invisibly in the command prompt, and launches the Web-based GUI into your browser.

  4. Here are the instructions to start the H2 database if your computer has Windows XP. SKIP THIS STEP IF YOUR COMPUTER HAS WINDOWS VISTA OR LATER AND YOU DID THE PREVIOUS STEP.

    Using Windows Explorer or My Computer, navigate to {Lab Installation Directory}/lib/h2/h2-1.3.161.jar and double-click on the JAR - this starts the database running and opens a Web-based administration GUI.

  5. In the H2 GUI, set the JDBC URL to jdbc:h2:tcp://localhost/~/test, typing this VERY carefully.

    Set both the User Name and Password to sa, then press Connect.

    Leave the H2 GUI running for future steps.

  6. Next, define a JNDI data source for your program:

    1. In Eclipse, in the Project Explorer, expand the Servers folder (NOT the Servers tab at the bottom). Then expand the entry for the TomEE server.

      Open the tomee.xml file into the editor, and at the bottom of the editor, press the Source tab.

    2. Enter the following, immediately above the tomee close tag at the bottom.

      <Resource id="ExampleDS" type="DataSource">
          JdbcDriver org.h2.Driver
          JdbcUrl jdbc:h2:tcp://localhost/~/test
          UserName sa
          Password sa
      </Resource>           
                 
                 

    3. Save and close the tomee.xml file.

    4. At the bottom of the Eclipse window, in the Servers tab (NOT in the Project Explorer), right-click on the server and choose Publish to ensure that Eclipse publishes the configuration to the server.

    5. Start the server. Ensure that there are no errors in the Console, then search the Console for ExampleDS to ensure that the data source was defined correctly.

Part 2: Writing an Entity POJO

In this part, you will write a plain old Java class as an entity that can be used with Java Persistence.

Steps:

  1. As before, create a Dynamic Web project named Lab07Web. Be sure to create the Web deployment descriptor.

  2. Next, configure the project to support JPA:

    1. In the Project Explorer, right-click on the project and choose Properties, then click the Project Facets entry.

    2. Put a checkmark in the JPA entry, then set the version to 2.0.

      Near the bottom, click the Further configuration required link to start the wizard.

    3. On the first wizard page, in the Platform section, select EclipseLink 2.4.x/2.5.x.

      In the JPA Implementation section, select Disable Library Configuration, then press OK twice.

    4. Look in the project's Java Resources folder. Note that it has a src folder with an embedded META-INF folder. You will edit the persistence.xml file in this folder in a later step.

  3. Next, create an entity using an Eclipse wizard:

    1. Right-click on the src folder and choose New - JPA Entity to start the wizard.

    2. On the first wizard page, for the Java package, enter part1.

      For the Class name, enter Order and then press Next.

    3. On the next page, in the Table Name section, uncheck the Use default box and for the Table Name, enter Orders (ORDER is a keyword in SQL and should not be used as a table name).

      In the Entry Fields section, press the Add button and for the Type, select int and for the Name, enter orderNumber and press OK. Then put a checkmark in the Key column for this newly added field.

      Repeat the Add to define two more fields, neither of which should be part of the Key:

      Type            Name
      ----            ----
      double          amount
      java.util.Date  orderDate   -- browse for "Date"
                     

      Press Finish. Eclipse creates the entity class and opens it into the editor.

    4. Note the following:

      • The class is annotated with @Entity.
      • The class is annotated with @Table, specifying that the table name is not the same as the class name.
      • The orderNumber field is annoated with @Id.
    5. You need one more annotation to get this to work. Immediately before the orderDate field, tell Java Persistence how to store the date:

      @Temporal(TemporalType.DATE)
                     

      You will need to import javax.persistence.Temporal and javax.persistence.TemporalType.

  4. Next, you need to edit the persistence.xml file that configures Java Persistence (the create-JPA-project wizard created the file):

    1. In the Project Explorer, expand the META-INF folder and double-click on persistence.xml to open it into the editor.

    2. At the bottom of the editor, click the General tab, then in the General section at the top, change the Name to lab07.

    3. At the bottom of the editor, click the Connection tab. For the Transaction Type, select JTA.

      Then for the JTA data source, enter ExampleDS. This is the data source you configured to reference your H2 database.

    4. Click the Properties tab at the bottom of the editor window.

      Use the Add button to define the following properties:

      Name                   
      ----                    
      openjpa.jdbc.SynchronizeMappings            
      
      
      Value
      ------
      buildSchema(schemaAction='dropDB,add')
                     

      This property tells the OpenJPA provider to recreate the database every time the program starts. Note that this is OK for development and testing, but NEVER use this in production, as you will lose all existing data.

    5. Click the Source tab at the bottom of the window and examine the raw XML and ensure that you understand it.

      Be sure to save the file before continuing.

Part 3: Writing a Session EJB

In this part, you will write a stateless session EJB that will create and query Order entities. You will later create a servlet that invokes the stateless session EJB.

As you will learn later, by default, each session EJB method automatically comprises a transaction. Thus, your servlet will not need to explicitly start and commit transactions while creating or querying entities.

Steps:

  1. As in earlier labs, create a stateless session EJB according to these specifications:

    Java package name:     session
    Class name:            OrderSessionBean
    No-interface View:     unchecked
    Local interface name:  session.ManageOrders
             

  2. Complete the session/ManagerOrders.java interface by writing the following method definitions:

    public void insertOrders();
    public Order queryOrder(int orderNumber);
                              
             

  3. Complete the session EJB, OrderSessionBean.java:

    1. Use dependency injection to obtain a reference to the persistence manager:

      @PersistenceContext(unitName="lab07")
      private EntityManager entityManager;
                   

      Recall that you wrote a persistence.xml file ithat configured the persistence unit name to be lab07.

    2. Write empty implementation methods:

                   
      public void insertOrders()
      {
          
      }
      
      public Order queryOrder(int orderNumber)
      {
          return null;
      }             
                   
                   

    3. Complete the insertOrders method:

      • Create two Order entities and call their set methods to initialize all of their properties. You can use new java.util.Date() to provide the current date. Please ensure that the two orders have unique orderNumbers, since that's the primary key field.
      • Use the EntityManager to persist the two entities.

      Note that since this code is in a session EJB, the container, by default, runs each method invocation within a transaction. Thus, you don't need to begin and commit a transaction manually.

    4. Complete the queryOrder method:

      • Create a query:

        Query q = entityManager.createQuery(
            "SELECT o FROM Order o WHERE o.orderNumber = :orderNumber");                 
        q.setParameter("orderNumber", orderNumber);
                         

      • Execute the query and return the Order entity:

        Order o = (Order)q.getSingleResult();
        return o;
                         

      You will need to import javax.persistence.Query.

    5. Save all files and ensure that you have no errors.

Part 4: Writing a Servlet

In this part, you will write a simple servlet that exercises your Order entities by calling methods in the stateless session EJB.

Steps:

  1. As in earlier labs, right-click on the Web project's Java Resources/src folder and create a new servlet named OrderServlet in the servlets package. The new servlet should override only doGet.

  2. Complete the servlet:

    1. Define a private field of type ManageOrders (the EJB interface) and use dependency injection to initialize it.

    2. In the doGet method, set the content type and retrieve a PrintWriter:

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
                  

    3. Call the session EJB's insertOrders method.

    4. Call the session EJB's queryOrder method twice, retrieving two Order entities. You will need to specify the orderNumbers that you used to create the entities (look at the insertOrders implementation in OrderSessionBean.java).

      Then display each of the orders' properties to the Web page using code like:

      out.println("<p>Order number: " + 
              o1.getOrderNumber() + "</p>");
      out.println("<p>Amount: " + 
              o1.getAmount() + "</p>");
      out.println("<p>Date: " + 
              o1.getOrderDate() + "</p>");
                  
                  

  3. In the Project Explorer, right-click on the servlet and choose Run As - Run on Server to run the servlet. You should see the order information in the resulting Web page.

    Note: If you find that you made a mistake with the entity, you should stop the server pressing Ctrl+C on its command prompt and then press up arrow to recall the last command, then press Enter. Then right-click again and restart and test again. Since we are using a top-down approach, this will cause the server to drop and recreate the database tables.

  4. Next, use the H2 admin console that you opened in the Web browser earlier in the lab to view the database:

    1. In the console's toolbar, hover your mouse over the icons and find the Refresh icon, then press it.

    2. To examine table, press Clear, then in the entry box, enter SELECT * FROM Orders and press the Run (Ctrl+Enter) toolbar button. You should see two rows of Order information.

    3. You can leave the H2 admin console window up so that you can explore the database whenever you like.