In this tutorial, we will learn the very basics of the new persistence mechanism in EJB 3.

Before you get started, make sure that you have completed the previous tutorial (EJB 3 Development for Glassfish using Eclipse 3.2) in this series.

In this tutorial, we will create a very simple Entity class called Customer. We will insert a few customers into the database using the persistence API of EJB 3. We will also learn how to look up the data using primary key and update and delete the data. We will use the Derby database shipped with Glassfish.

Make sure that you are running the database server and the application server before starting this tutorial.

Create the Entity Class

In the Simple EJB Project, within the com.webage.ejbs package, create a new class called Customer.

In the Customer class, add the following import statement.

import javax.persistence.*;

Many of the annotations and classes for the persistence API will come from this package.

First, we must designate this class as an Entity. This is done using the @Entityannotation. Add this annotation at the class level as shown below.

public class Customer {

Next, we will make the Customer class implement Doing so will allow us to use this class are parameters to a remote business interface method. Add the code shown in bold face.

public class Customer implements Serializable {

Add the following two member variables. They will form the attributes (or database columns) for the entity.

private int id;
private String name;

Generate getter and setter methods for these fields (right click on the editor and select Source->Generate Getters and Setters).

The id field will act as the primary key column of the Customer. Declare that fact using the @Id annotation as shown below.

private int id;

Save changes. That’s it, the Entity class is now complete.

Create the persistence.xml File

The persistence.xml file must be created within the META-INF directory of the EJB module. This file defines persistence units. Each unit is basically a reference to the data source that will be used to access the database. The unit can also contain configuration such as the type of database (Oracle, MySQL etc.) and if database tables should be automatically created by the persistence engine.

Within Simple EJB Project, create a folder called META-INF. Within this folder, create a new file called persistence.xml. In that file, add the following content.

<persistence version="1.0"> 
 <persistence-unit name="my_persistence_ctx"> 
 <!--Use the java2db feature --> 
 <property name="toplink.ddl-generation" value="drop-and-create-tables"/> 
 <!-- Generate the sql specific to Derby database --> 
 <property name="" 

Note the following aspects of this file:

  1. The name of the unit is my_persistence_ctx. We will use this name to look it up from the code.
  2. The unit will use a data source with JNDI name jdbc/__default. This data source is automatically defined when Glassfish is installed. In real life, you will probably use a database such as MySQL, Oracle or DB2. In that case, you must first define a data source using the Glassfish administration console.
  3. We configure the persistence engine to automatically drop and create tables when the EJB JAR is deployed. This is a good choice during heavy development when the Entity classes are changing rapidly. If you do not wish the system to create tables, you can set the value of the toplink.ddl-generation property to none.
  4. We set the SQL dialect to be specific to Derby. Examples of other platform classes are “oracle.toplink.essentials.platform.database.DB2Platform” for DB2 and “” for Oracle.

Save and close the persistence.xml file.

Use the Entity from a Session EJB

We will use the Customer Entity from the SimpleBean session bean created in the first tutorial. First, we will insert a few customers to the database.

Open the business interface Add a new method as follows:

public void createCustomers();

Save and close the file.

Now, open the implementation class Add a new member variable to obtain reference to the persistence unit as follows:

EntityManager em;

Note, how we use the name of the persistence unit here.

Add this method:

public void createCustomers() {
 Customer c1 = new Customer();


The call to the EntityManager.persist() method will result in a SQL INSERT statement.

Save and close the file.

Deploy the EJB JAR

Deploy the EJB JAR file by exporting Simple EJB Project into the autodeploy folder as already mentioned in the previous tutorial.

Write the Client

In the Simple Client Project, open Below this line:

SimpleBean bean = (SimpleBean) ctx.lookup("ejb/SimpleBeanJNDI");



Save the file.

Run the Client

Run the TestClient class as already described in the previous tutorial.

Note, you can run the client only once. Running it again will cause primary key collision and the customer can not be added.

Inspect the Database

In this step, we will inspect the Derby database using the ij command line tool.

Open a command window. Change directory to C:glassfishjavadbframeworksNetworkServerbin.

Using notepad open the ij.bat file:

notepad ij.bat

Replace the following line:



set DERBY_INSTALL=C:glassfishjavadb

Save and close the file.

Now, run the ij command.


In the ij> command prompt, enter this command:

connect 'jdbc:derby://localhost:1527/sun-appserv-samples';

This will cause the client to connect to the sun-appserv-samples database. This database is used by the jdbc/__default data source. Note: This database is created the first time the EJB JAR file is deployed. The database is not created as a part of Glassfish installation.

Now, enter the command:

select * from customer;

Make sure that you can see the customer that was added.

We will now delete the customer so that we can finish the rest of the tutorial without any problem.

delete from customer;

Exit out of ij by entering:


Add More Database Access Feature

Now, we will add the ability to retrieve a Customer, update and delete it. This can be done entirely using the session EJB. We don’t have to change the Entity class.

First, add the following methods to the business interface

public Customer getCustomer(int id);
public void updateCustomer(Customer c);
public void deleteCustomer(Customer c);

Save and close the file.

Implement these new methods in as follows.

public Customer getCustomer(int id) {
 Customer c = em.find(Customer.class, new Integer(id));

 return c;

public void updateCustomer(Customer c) {

public void deleteCustomer(Customer c) {
 c = em.merge(c); //Must do this


The EntityManager.merge() call will flag the Customer instance so that the data is used to update the underlying row. The updateCustomer() method relies on this behavior. The actual SQL UPDATE statement is issued at a later time, before the transaction is completed. The EntityManager.remove() call, results in a SQL DELETE statement to be executed. Note: To remove an entity, we must use a managed instance. The Customer object instance passed to the deleteCustomer() method is called detached as it is not currently managed by the EntityManager in any way. Merging will make the instance managed. A managed instance is always associated with the underlying row in the table. That means, the merge call will implicitly do a SELECT SQL call (if the instance is currently detached).

Save and close the file. Re-deploy the EJB JAR file.

Update the Client


Below the line:



Customer c = bean.getCustomer(1);
System.out.println("Retrieved customer: " + c.getName());

Save changes.

Make sure that you have re-deployed the EJB JAR file. Now, run the client. The Consoleview should show the message:

Retrieved customer: XYZ

Also, now you can run the client repeatedly as we delete the customer data.


In this tutorial, we learned the very basics of the new persistence API available from EJB 3. As you can see, it is very easy to add database access to your program.