Using Java Persistence API for Java SE 7 Desktop applications in NetBeans 7- Part 2

Overview

    Purpose

    This tutorial covers  implementing CRUD database operations using Java Persistence API(JPA) for desktop applications.

    Time to Complete

    Approximately 45 minutes.

    Introduction

    This example demonstrates implementing CRUD database operations using  Java Persistence API  for desktop applications.

    The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. Some of the features of JPA are

  • You won't have to create complex data access objects (DAO).
  • The API helps you manage transactions.
  • JPQL is database agnostic, freeing you from vendor-specific code.
  • JPQL is portable whereas SQL is not.
  • You can avoid SQL in preference to a query language, JPQL that uses your class names and properties.
  • You can also use the Java Persistence API for desktop application persistence.

    In this tutorial, you will create java client programs to demonstrate the following CRUD operations- Retrieve, Update and Delete operations using Entity clases. The Create operation is covered in the Part-1 of this OBE.

    The Part-1 of this OBE covers the following:

    • Create a database connection
    • Generate Entity classes for tables in the database
    • Create Operation- persist data in the database

    Hardware and Software Requirements

    The following is a list of hardware and software requirements:

    • Download and install Java JDK 7 from this link.
    • Download and install NetBeans 7.2  from this link.

    Prerequisites

    Before starting this tutorial, you should:

    •  Have the software installed as listed under Hardware and Software Requirements section.
    •  Start the NetBeans IDE.
    • Start the Java DB database server from NetBeans.
      1.   Click Services tab.
      2.   Expand Databases node.
      3.   Right-click Java DB icon.
      4.   Select Start Server
    •  Download and unzip the PersistenceDemo.zip file that contains a NetBeans project you need to complete this tutorial.
    • Create playerDB database, follow the steps in Creating a database connection section of Part-1 of the OBE
    • Create tables and populate them with data in playerDB database.
      1. Download and unzip the playerDB.zip
      2. In NetBeans select File > Open File .
      3. In the file browser navigate to the directory, which contains playerDB.sql.
      4. Select playerDB.sql and click open. The script automatically opens in the SQL Editor.
      5. Select jdbc:derby://localhost:1527/playerDB in Connection drop-down box in the SQL Editor toolbar.
      6. Click the Run SQL icon to execute the script.

Retrieve Operation

    The Java Persistence API (JPA) provides various ways to retrieve objects from the database. The retrieval of objects does not require an active transaction because it does not change the content of the database.  In this section you create a  Java class RetrievePlayers.java to  demonstrate the following

    • Retrieve a single record  from Player table and display in the console.
    • Retrieve all  records  from the Player table and display in the console.

    Retreiving a single record from Player

      In this section you create a  Java class RetrievePlayers.java to  retrieve a  record  from the Player table using find method and display in the console.

      In the NetBeans IDE, open the provided  PersistenceDemo project, and expand Source Packages > demo.

      In the Projects window, double-click Player.java to open it in the code editor window.

      Delete any IDE generated code in the toString method  and add the below code.

      @Override
          public String toString() {
              String player = String.format("[Jersey Number: %d, First Name: %s, Last Name: %s]", jerseynumber, firstname, lastname);
              return player;
          }


      Overriding the toString method in the entity class, Players.java  to display the details of the Players objects to the console.

      To create RetrievePlayers.java, perform the following steps:

      a.  In the Project Window, right-click PersistenceDemo project and select New > Java Class.


      Specify the Java Class  details as follows:

      Class Name: RetrievePlayers

      Package Name: demo

      Click Finish.

      Edit RetrievePlayers.java

      a. Import the following packages


      import javax.persistence.*;


      b. Create main method and add the following lines of code.

      public static void main(String[] args) {
         
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceDemoPU");
      EntityManager em = emf.createEntityManager();
      }


      The above code creates an instance of EntityManager. An EntityManager provides methods to begin and end transactions, to persist and find entities and also to create and execute queries.


      c. Add the below code to main method  to retrieve a Player  object whose primary key is 3.

              Player p = em.find(Player.class, 3);
              System.out.println(p.toString());


      The above code demonstrates retrieving objects from the database using find method.  Every entity object can be uniquely identified and retrieved by the combination of its class and its primary key.


      d.  Add  the below statements to the main method.

        em.close();
        emf.close();



      The above statements close the  connection to the database.

      Add the Java DB client jar to connect to the Java DB database server. Complete the following steps:

      Right-click Project > Project Properties> Libraries.

      Select Add JAR/Folder.

      Browse to C:\Program Files\Java\jdk1.7.0_05\db\lib\derbyclient.jar

      Click Open > Click OK.

      In the Projects window, right-click RetrievePlayers.java and select Run File from the right-click menu.


      Verify the output.

      Examine the PersistenceDemo tab in the Output window.


      Details of the Player object with primary key 3  is  displayed in the console.


    Retrieving all records from Player

      In this section you modify  RetrievePlayers.java to retrieve all records from the Player table using JPQL query and display in the console.

      1. Import the following package

      import java.util.List;

      2. Delete the following code from main method.

      Player p = em.find(Player.class, 3);
      System.out.println(p.toString());

      3. Add the following code to the main method.

           Query query = em.createQuery("SELECT p FROM Player p", Player.class);
              List<Player> playerList = query.getResultList();
              System.out.println("Player List:");
              for (Player p : playerList) {
                  System.out.println(p.toString());
              }

      The above code creates  a JPQL query to fetch all the objects from the Player entity and display in the console.

      4. In the Projects window, right-click RetrievePlayers.java and select Run File from the right-click menu.

      8. Verify the output.

      Examine the PersistenceDemo tab in the Output window.

      The details of all Player objects are displayed in the console.

Update Operation

    In this section, you create a java class, UpdatePlayers.java to demonstrate updating an existing Player object. You have to obtain a managed entity object  and modify it within an active transaction.

    To create UpdatePlayers.java, perform the following steps:

    In the Project Window, right-click PersistenceDemo project and select  New > Java Class.


    Specify the Java Class  details as follows:

    Class Name: UpdatePlayers

    Package Name: demo

    Click Finish.


    Edit  UpdatePlayers.java

    a. Import the following packages

    import javax.persistence.*;


    b. Create main method and add the following lines of code.

    public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceDemoPU");
    EntityManager em = emf.createEntityManager();
    }


    To update a row in Player table.    

    Add the following code to the main() method.

             em.getTransaction().begin();
            Player p = em.find(Player.class, 5);
            p.setJerseynumber(60);
            em.merge(p);
            em.getTransaction().commit();


    The above code updates the jerseynumber field to 60  for the row with primary key, 5  in the Player table.
    You can update the entity and merge it back into the persistence context with the merge method. You can use JQPL to perform an update but the more efficient (and OO) way is to use merge.
    JPQL update is typically recommended for bulk update operations.

    Add the below statements to the main method.

    em.close();
    emf.close();




    To execute the program.

    In the Projects window, right-click UpdatePlayers.java and select Run File from the right-click menu.



    Verify the output. Examine the contents of the database.

    a. In the Services window, expand the jdbc:derby://localhost:1527/playerDB connection under the Databases node.
    b. Right-click the connection and select Refresh.
    c. Expand the FRED schema > Expand Tables Node > PLAYER Table.
    d. Right-click PLAYER table node and select View Data.

    You see the row with ID 5 updated in the Player table.

Delete Operation

    In this section, you create a  java class, DeletePlayers.java to delete  an object from the database. To delete an object, you need to obtain an object (usually by retrieval) and invoke the remove method within the context of an active transaction.  The entity object marked for deletion by the remove method is physically deleted from the database when the transaction is committed.

    To create DeletePlayers.java, perform the following steps:

    a. In the Project Window, right-click PersistenceDemo project and select New > Java Class.

    b. Specify the Java Class  details as follows:

    Class Name: DeletePlayers

    Package Name: demo

    Click Finish.


    Edit  DeletePlayers.java

    a. Import the following packages

    import javax.persistence.*;

    b. Create main method and add the following lines of code.

    public static void main(String[] args) {

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceDemoPU");
    EntityManager em = emf.createEntityManager();

     }


    To delete a specific record in the Player table.

    Add the following code to the main() method.

       em.getTransaction().begin();
       Player player = em.find(Player.class, 5);
       if (player != null) {
       System.out.println(player.toString());
       em.remove(player);
       }
       em.getTransaction().commit();



    The above code retrieves  a Player object with playerID equals to 5 from the Player table using the find method and  then the  object is deleted using the remove method.


    Adding the below statements to the main method.

      em.close();
     emf.close();



    To execute the program.

    In the Projects window, right-click DeletePlayers.java and select Run File from the right-click menu.


    Verify the output.

    a. Examine your console, the deleted Player object is displayed.



    b. Examine the contents of the database.

    • In the Services window, expand the jdbc:derby://localhost:1527/playerDB connection under the Databases node.
    • Right-click the connection and select Refresh.
    • Expand the FRED schema > Expand Tables Node >PLAYER Table.
    • Right-click PLAYER table node and select View Data.

     
    You see the row with playerID equals to 5 deleted from the Player table.

Summary

    In this tutorial, you have learned how to:

     

    • Define persistable entities in your application
    • Use the API in  Java SE environment.
    • To implement CRUD operations.
    • How to configure your NetBeans integrated development environment (IDE) to use the API.

    Resources

    Credits

    • Lead Curriculum Developer: Anjana Shenoy

To help navigate this Oracle by Example, note the following:

Hiding Header Buttons:
Click the Title to hide the buttons in the header. To show the buttons again, simply click the Title again.
Topic List Button:
A list of all the topics. Click one of the topics to navigate to that section.
Expand/Collapse All Topics:
To show/hide all the detail for all the sections. By default, all topics are collapsed
Show/Hide All Images:
To show/hide all the screenshots. By default, all images are displayed.
Print:
To print the content. The content currently displayed or hidden will be printed.

To navigate to a particular section in this tutorial, select the topic from the list.