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


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

Time to Complete

Approximately 30 minutes.


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:



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.



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.

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

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


To create playerDB database, perform the following steps:

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

b. Enter the following information for the database:

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

c. Click OK.


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


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

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

b. Select Connect.


Create tables and populate them with data in playerDB database.

a. In NetBeans select File > Open File .

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.

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.


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.

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

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

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

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.



Create new Java Project .Select File > New Project .



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



Perform the following steps:

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


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



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.

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

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



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


In the Mappings Window, click Finish with default selection.


Verify the creation of Entity Classes.

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


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.


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.

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

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, contains the mappings to the table, PLAYER in the form of annotations.


Create Operation


To create the client program, perform the following steps:

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

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

c. Click Finish.

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


Import the following classes:

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


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();


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.


Add below code to the main method.


Player p1 = new Player();
p1.setLastspokenwords("I am in the best form");

Player p2 = new Player();
p2.setLastspokenwords("I will be back");



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


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.

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


In the Projects window, right-click 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 the 2 rows inserted in the PLAYER table.



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.



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