Simple CRUD Example – Part 1

If you have ever developed a web application you’ll know that most of the code you write is not clever business logic that’s doing complicated calculations but actually fairly simple CRUD (Create, Reuse/Retrieve, Update, Delete) code. Since this is the type of code that gets written all the time it makes sense to know it inside and out and make sure it’s correct and optimized. This series of articles takes you through the creation of a simple CRUD application using the following technologies:

  • Java Persistence API (JPA) 2 – stores and retrieves entities (objects) from a database. Provides a standardizes API on to the actual provider which is EclipseLink by default in GlassFish 3.1.
  • JavaServer Faces (JSF) 2 – provides a clean and simple method of producing an HTML front end. Handles data validation and the request-response cycle.
  • Enterprise JavaBeans (EJB) 3.1 – powers the business logic of the application. Gives access to entities and handles transaction management.

We’ll be developing under NetBeans 7 and deploying to GlassFish 3.1. I’m going to assume a certain amount of familiarity with both pieces of software (or at least the drive to explore them) or this tutorial would take forever. The first thing to do is create a new database, I’ll be developing against the built in Derby (Java DB) database to keep things simple, obviously a real application would probably deploy against something like MySQL or MS SQL.

Creating the Database

​The database can be created under either NetBeans or GlassFish. I’m going to create it under GlassFish as I’ve had problems in the past creating us under NetBeans (GlassFish for some reason refused to connect to the database). You also need to use GlassFish to configure the persistence unit so it’s quicker to do everything from one place.

Using GlassFish to Create the Database

We aren’t directly creating the database using GlassFish, what we are acutally doing here is creating a JDBC connection pool and asking Debry to create the database the first time we try to access it. This little bit of magic is done by specifying a create=true arguement at the end of the connection string.

With GlassFish running open the administartion console (this is easily done through NetBeans) and then select the JDBC Connection Pools node. Click New at the top of the table. Give the pool a name such as CrudExamplePool, set it’s type to DataSource and then select Derby from the list (or JavaDB they produce the same end result). On page two just fill in a username, password and database name (unless you’ve changed anything on your system). Finally, click Add Property which will create a new blank field at the top of the table. In this new field set the key as connectionAttributes and the value as ;create=true. Note that value starts with a semi-colon.

Click finish and then ping. If the ping succeeds you will find a new database in your database directory.

Using NetBeans to Create the Database

Under the services tab in NetBeans locate the Databases icon and expand it to display the Java DB node. Right click and create a new database called CrudExample. Set a user name and password such as “user” and “pass” and optionally set a location for the database. Once it’s created right click and connect.

Displaying the Database

Under the Java DB node you should now see a new database called CrudExample. You may need to restart NetBeans to make this database show up, there seems to be a problem with refreshing. Right click on the node and connect. This will createa a new node under databases with a connection string looking something like this:

jdbc:derby://localhost:1527/CrudExample [user on USER]

Your new example database is ready to go.

Configuring the Persistence Unit

A persistence unit when used in a Java EE environment requires a JDBC resource to be bound into the JNDI directory on the server where it is being used. This requires the creation of a connection pool and then the JDBC resource to use that connection pool. Creating the connection pool is covered above in the Using GlassFish to Create the Database section.

Once you have the CrudExamplePool created select the JDBC Resource node in GlassFish and press New. In the JNDI Name  field enter the name that will bind the connection pool such as jdbc/CrudExamplePool. Select the pool that will be bound and press Ok.

Back in NetBeans create a new Maven Web Application and expand the Other Sources node in your project. If this node doesn’t exist select the Files tab, expand src then main and create a directory called resources. Under Other Sources create a folder called META-INF and then a new file called ​persistence.xml.

The ​persistence.xml​ file holds the configuration for your applications persistence unit and should look something like this:

	<?xml version="1.0" encoding="UTF-8"?>
	<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	  <persistence-unit name="CrudExamplePU" transaction-type="JTA">
	    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	    <jta-data-source>jdbc/CrudExamplePool</jta-data-source>
	    <exclude-unlisted-classes>false</exclude-unlisted-classes>
	    <properties>
	      <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
	      <property name="eclipselink.target-database" value="DERBY"/>
	      <property name="eclipselink.logging.level" value="INFO"/>
	    </properties>
	  </persistence-unit>
	</persistence>

The most important setting is the jta-data-source setting which points the persistence unit at the connection pool you created above.  Since we are developing in a Java EE environment we have set the transaction type to JTA. The ddl-generation setting is current set to drop and create which is useful while we are developing an application as it ensures that we always have a fresh database to damage erm I mean work with.

Note: JPA has a sneaky little optimization that I didn’t know about. If there are no references to the EntityManager that is created from the PersistenceUnit the system won’t create the any of the tables automatically. Presumably it’s clever enough to know that they could never be accessed. That had me going for a while.

The exclude-unlisted-classes setting is important as it causes JPA to scan the classpath looking for classes that are marked as entities. If this setting is missing or set to true you have to list every class that you want to use as an entity.

At this point you are basically ready to go. This article has already gone on too long so I’ll bid you farewell until the next article which will cover setting up the application.