Using Java Persistence API for Java SE 7 Desktop applications in NetBeans 7

Purpose

This tutorial demonstrates setting up Java Persistence API for Java SE 7 desktop applications in NetBeans 7.

Time to Complete

Approximately 30 minutes.

Overview

The Java Persistence API(JPA) provides an object/relational mapping facility for managing relational data in Java applications. JPA is a lightweight, POJO-based framework for object-relational mapping. The mapping between Java objects and a relational database is done using annotations and/or XML deployment descriptors. Though JPA is a part of EJB 3 Specification it can be used in Java SE applications, outside of the Java EE environment .

In this tutorial, you will create and configure a persistent Unit using JPA. You will

 

Software and Hardware Requirements

The following is a list of software requirements:

Prerequisites

 

Creating a database connection

Java DB database server is part of NetBeans. We will use Java DB as the database server . The following steps demonstrate creating the database playerDB.

 

1 .

To start the Java DB Database from NetBeans, perform the following steps.

a. Click Services tab.
b. Expand Databases node.
c. Right-click Java DB icon.
d. Select Start Server.

Show Screenshot for Step

Note the following output in the Output window, indicating that the DB server has started:

Show Screenshot for Step

Note that the DBserver version could vary from the version shown in the screenshot depending on the JDK build updates.

2.

To create playerDB database, perform the following steps:


a. Right-click Java DB icon, select Create Database.

Show Screenshot for Step


b. Enter the following information for the database:

Database Name: playerDB
User Name: Fred
Password: Fred
Confirm Password: Fred

c. Click OK.

Show Screenshot for Step

 

This creates the database and adds a connection for the database under the Databases icon.

Show Screenshot for Step

3 .

To connect to the newly created database playerDB, perform the following steps :

a. Right-click jdbc:derby://localhost:1527/playerDB connection.

b. Select Connect.

Show Screenshot for Step

4.

Create tables and populate them with data in playerDB database.

a. In NetBeans select File > Open File .

Show Screenshot for Step

b. In the file browser navigate to the directory, where you unzipped the files from the Prerequisites section and

select playersDB.sql

c. Click Open. The script automatically opens in the SQL Editor.

Show Screenshot for Step

d. Select jdbc:derby://localhost:1527/playerDB in Connection drop-down box in the SQL Editor toolbar.

e. Click the Run SQL icon to execute the SQL statement.

Show Screenshot for Step

5.

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. You see the nodes for the Tables, Views, and Procedures.

Show Screenshot for Step

d. Expand the Tables node to see the PLAYER, TEAM tables.

Show Screenshot for Step


e. Right-click PLAYER table node and select View Data.

Show Screenshot for Step

f. A SQL command window opens and executes an SQL command to display the data in the table.

Show Screenshot for Step

g. Repeat the previous step for the TEAM table.

Generating Entity Classes from Database

 

The Java Persistence API requires that you identify the classes that you will store in a database. The API uses the term entity to define classes that it will map to a relational database. You identify persistable entities and define their relationships using annotations. An entity represents a table in a relational database. Each entity instance corresponds to a row in the table. An Entity is coded as a POJO.

 

1.

Create new Java Project .Select File > New Project .

Show Screenshot for Step

 

2.

Select Java from the Categories column and Java Application from the Projects column and then click Next.

 

Show Screenshot for Step

3.

Perform the following steps:

a. Name the project PersistenceDemo.
b. Uncheck the Create Main Class check box.
c. Click Finish

Show Screenshot for Step

4.

Right-click PersistenceDemo Project and select New > Entity Classes From Database.

Show Screenshot for Step

 

5.

Enter the following information to create Entity classes:

a. In the Database Connection field select jdbc:derby://localhost:1527/playerDB[Fred on FRED] from the drop-down.

Show Screenshot for Step

b. You see PLAYER and TEAM tables in Available Tables category
c. Click Add All

Show Screenshot for Step

d. You see both the tables PLAYER and TEAM in Selected Tables Category
e. Click Next

Show Screenshot for Step

 

6.

In the Entity classes Window, enter the Package Name as demo and click Next.

Show Screenshot for Step

7.

In the Mappings Window, click Finish with default selection.

Show Screenshot for Step

8.

Verify the creation of Entity Classes.

a. Select the PersistentDemo Project.
b. Expand the demo package, you see Team.java and Player.java created.

Show Screenshot for Step

 

The above set of entities created in the application is called a persistence unit. Persistence units are configured in an XML file placed in the META-INF folder. It is used to specify the persistence provider name, entity class names and properties like the database connection URL, driver, user, password.

Show Screenshot for Step

9.

Name the Persistence Unit name as PersistenceDemoPU in the persistence.xml file.

a. Right-click persistence.xml and select Open to view it in the code editor window.

Show Screenshot for Step

b. Select Source tab .
c. Verify the name of persistence Unit is PersistenceDemoPU as shown below.

Show Screenshot for Step

Implementing CRUD operations using JPA

 

Entity objects are in-memory instances of entity classes which represent physical objects in the database. In JPA you can use entity objects for many operations, including Creating , Retrieving, Updating and Deleting database objects. We need three artifacts to implement the CRUD operations using JPA:

1. An Entity class
2. A persistence.xml file
3. A class (or client) through which we insert, update or find an entity.

The following section demonstrates Create operation, to persist Player entity objects into playerDB database. The Entity class, Player.java contains the mappings to the table, PLAYER in the form of annotations.

 

Create Operation


1 .

To create the client program CreatePlayers.java, perform the following steps:

a. Right-click PersistenceDemo project and select New > Java Class.

Show Screenshot for Step

b. Save the class as CreatePlayers and select package name as demo.

Show Screenshot for Step

c. Click Finish.

d. Right-click CreatePlayers.java and select Open to view it in the code editor window.

Show Screenshot for Step

2 .

Import the following classes:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;


Show Screenshot for Step

3 .

Create main method in the class and add the following lines of code.


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

 

Show Screenshot for Step

The above code demonstrates creation of an EntityManager instance. To persist a new entity, you need an EntityManager instance. EntityManagerFactory is a factory for creating an EntityManager. EntityManager manages entities and it is responsible for their addition, updating and deletion. Since EntityManager instances represent a persistence unit, you must provide the persistence unit name. In this example PersistenceDemoPU is the persistence unit name which is declared in the persistence.xml file along with other properties.

4 .

Add below code to the main method.

em.getTransaction().begin();

Player p1 = new Player();
p1.setId(5);
p1.setFirstname("Ian");
p1.setJerseynumber(30);
p1.setLastname("Thorpe");
p1.setLastspokenwords("I am in the best form");
em.persist(p1);

Player p2 = new Player();
p2.setId(6);
p2.setFirstname("Deigo");
p2.setJerseynumber(40);
p2.setLastname("Maradona");
p2.setLastspokenwords("I will be back");
em.persist(p2);

em.getTransaction().commit();

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

The above code creates a transcation, 2 objects of the Player class which is persisted
as 2 rows in the Player Table.

Show Screenshot for Step

5 .

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

1) Right-click Project > Project Properties> Libraries.

2) Select Add JAR/Folder.

Show Screenshot for Step

3) Browse to C:\Program Files\Java\jdk1.7.0_01\db\lib\derbyclient.jar
4) Click Open > Click OK.

Show Screenshot for Step

6 .

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

Show Screenshot for Step

 

7 .

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 the 2 rows inserted in the PLAYER table.

Show Screenshot for Step

 

Summary

This tutorial covers some of the capabilities of JPA in Java SE environment . The API simplifies object persistence by enabling use of POJOs throughout your application and in your database.

Resources

Credits

Hardware and Software Engineered to Work Together Copyright � 2011, Oracle and/or its affiliates. All rights reserved