Using Java Persistence in a Web Application
This document is a basic introduction to using the Java Persistence API in a web application and demonstrates how
the development process using the JavaTM Platform, Enterprise Edition 5 ("Java EE 5") technology
simplifies the development of Java applications.
In this document you will use the IDE to create
a web application that will access a database.
In the web application, you will use the IDE to generate entity classes corresponding to tables in a database.
You will then create a servlet that displays the information in the database.
The application uses Java Persistence to manage the database transaction.
This document uses the NetBeans IDE 6.5 Release, but the steps generally apply to all 6.x versions of the IDE.
To see how to connect to a database in a Visual Web application, see
Using the Java Persistence API Within a Visual Web JSF Application.
Tutorial Exercises
To follow this tutorial, you need the following software and resources.
Prerequisites
This document assumes you have some basic knowledge of, or programming experience with, the following technologies:
- Java Programming
- NetBeans IDE
Configuring the IDE to Use the Application Server
For this tutorial you must have an instance of Glassfish V2 or
the Sun Java System Application Server Platform Edition 9 registered with the IDE.
In this exercise you will register the application server with the IDE.
If the application server is already registered and visible in the Services window, you can go to
Setting Up the Web Application Project.
- Choose Tools > Servers from the main menu.
- Click Add Server. Select your application server (GlassFish or Sun Java System Application Server) and give a name
to the instance. Then click Next.
- Specify the installation directory of the application server (for example, C:\Sun\Appserver).
- Leave the Register Local Default Domain radio button selected and select a domain.
- Optionally, click Next and enter your administrator username and password.
If you do not want to store the username and password in your IDE user directory, you can leave these fields blank.
The IDE will prompt you every time it needs the information.
Note: The default admin password is adminadmin.
- Click Finish. The IDE registers the server and lists it under the Servers node in the Services window.
Summary
In this exercise you registered the application server with the IDE.
Setting Up the Web Application Project
In this example developing for the Java EE 5 platform, you do not need a full enterprise application because you do not
need an EJB module or session beans.
Instead, you can create a simple web application and put the entity classes directly in the web application.
- Choose File > New Project (Ctrl-Shift-N).
Select Web Application from the Java Web category.
- Type CustomerBook for the project name and set the project location.
- Deselect the Use Dedicated Folder option, if selected.
(This option is not available if you are using NetBeans IDE 6.0.)
For this tutorial there is little reason to copy project libraries to a dedicated folder because
you will not need to share libraries with other users or projects.
Click Next.
- Set the server to GlassFish and set the Java EE Version to Java EE 5. Click Finish.
Summary
In this exercise you created a Java EE 5 web application which will contain the entity classes and servlet.
Coding the Web Application
Generally some basic setup is necessary before you can start coding the web application.
This would include establishing a connection with the database and creating a connection pool and data source.
Because you are using the jdbc/sample database that comes bundled with the IDE, much of this is already configured.
The connection to the database is already registered with the IDE and the connection pool and data source are already created.
You can view the connection and data source properties in the Services window.
If you want to use a different database, you need to register a connection and create a data source for the database.
Once the setup is complete, development for the Java EE 5 platform is much easier than before because
the container does more of the work.
Because the container is managing persistence,
you do not need to edit any deployment descriptors to configure the CMP mappings or specify the finder methods.
In fact, in this example you do not need any deployment descriptors at all.
In the Java EE 5 platform, persistence is no longer limited to an EJB component.
Java EE 5 introduces the Java Persistence API, which can be used by non-EJB components, such as a web application.
Java EE 5 technology also eliminates the need for a lot of the
boilerplate code needed in J2EE 1.4 development. EJB development has been streamlined so that fewer interfaces are needed,
lookup is simpler, and annotations make component definition and resource injection simple and clear.
Managing Persistence
To manage persistence in the application you only need to create a persistence unit, specify which data source and entity manager to use, and
then let the container do the work of managing entities and persistence.
The container discovers the entity beans at runtime.
You create a persistence unit by defining it in persistence.xml.
The project does not contain a persistence.xml yet so you need to create it.
The persistence.xml file is created automatically when you add a persistence unit to the project with the New Persistence Unit wizard.
The wizard will help you define the properties of the persistence unit.
You can also create a persistence unit in the New Entity Class wizard.
When creating an entity class, the wizard will prompt you to create a persistence unit if one does not exist.
- Choose New File (Ctrl-N) to open the New File wizard.
- From the Persistence category, select Persistence Unit and click Next.
- Leave the default name for the persistence unit suggested by the wizard.
- Use the TopLink (default) listed in the Persistence Provider drop-down list.
The default provider is the TopLink Essential.jar.
TopLink Essential.jar contains the libraries for Java Persistence.
Our entity manager is located in TopLink Essential.jar.
- Use the default jdbc/sample data source listed in the Data Source drop-down list.
The default data source jdbc/sample is used to connect to the Java DB database that is bundled
with GlassFish application server.
- Click Finish.
When you click Finish, persistence.xml is created for your project and opens in the editor.
You can click XML in the toolbar of the editor to see the XML view of persistence.xml.
This file contains all the information the Java EE 5 container needs to manage the entities
and persistence of our application.
Creating the Entity Classes
When developing for the J2EE 1.4 platform, when you created entity beans you placed them in an EJB module
even when the application was a simple web application.
Each entity bean required several interfaces, and you had to configure
the deployment descriptors in ejb-jar.xml to define the entity beans,
the interfaces, persistence and finder queries for each entity bean.
In Java EE 5, instead of creating entity beans and putting them in the EJB module,
you can use simple entity classes, and the entity classes can be placed anywhere in a Java EE 5 application.
Writing classes for Java EE 5 applications is also easier than it was for the J2EE 1.4 platform because you can use annotations to
define components and inject resources.
You will now use the Entity Classes from Database wizard to create the entity classes based on the relational database.
- Start the Java DB database server.
- Choose New File (Ctrl-N) to open the New File wizard.
Select Entity Classes from Database from the Persistence category and click Next.
- In the Entity Classes from Database wizard, select the jdbc/sample data source for our database from the Data Source drop-down list
and supply the password if necessary. (The password should be "app".)
When you select the data source, a list of available tables appears in the Available Tables pane.
- Select the CUSTOMER table from the Available Tables and click Add.
When you click Add, any tables related to the selected table are also added.
In this example, the DISCOUNT_CODE table is also added. DISCOUNT_CODE table is greyed-out because it is referenced
by CUSTOMER table and an entity class for it must be generated in order to generate the Customer entity class.
When you hover your mouse over a greyed-out table in the Selected Tables pane, a tooltip appears that displays the name of the table that references the greyed-out table.
- Click Next.
The wizard displays the selected table and any related tables.
The wizard also displays the entity classes that will be created based on the selected tables.
If you want to modify the name of the class that will be generated, you can type the name in the Class Name field.
- Type ejb as the package for the generated classes. Click Finish.
When you click Finish, the IDE generates entity classes for the CUSTOMER table and the tables related
to CUSTOMER table. If you expand the ejb source package in the Projects window
you can see that the IDE created the Java classes Customer.java and DiscountCode.java.
You can see that the IDE created only two classes, one for each of the database tables.
If you look at Customer.java in the Source Editor, you will notice that the @Entity annotation is
used to declare the class an entity class.
Other annotations provide additional information such as the
database table and the columns that the entity class and its properties are mapped to.
You will also notice that much of the boilerplate code commonly found in entity beans is gone.
Methods such as ejbRemove, setMessage, setSessionContext, ejbActivate, and ejbPassivate
are no longer needed in your entity class in Java EE 5.
Coding the Servlet
You now need to add a servlet to the web application.
Instead of adding resource creation and lookup code to the servlet, with Java EE 5 you can use resource injection to move that work to the container.
You can use annotations to inject resources directly into the servlet, and
the container will manage the creation and lookup of the requested resource.
In this case, you want to use an entity manager as specified in the persistence unit.
- Right-click the project node in the Projects window and choose New > Servlet.
- In the New Servlet wizard, name the servlet CustomerDetails and put the servlet into a package named web. Click Finish.
When you click Finish, CustomerDetails.java opens in the Source Editor.
- In the source editor, right-click in CustomerDetails.java and choose Persistence > Use Entity Manager to
inject the PersistenceContext in the class. The IDE adds the following annotation that specifies the persistence unit used by the servlet.
The annotation is added above the class declaration.
@PersistenceContext(name = "persistence/LogicalName", unitName = "CustomerBookPU")
The IDE also adds the following annotation injecting a resource for managing transaction boundaries:
@Resource
private javax.transaction.UserTransaction utx;
If you expand the editor fold you can see that the IDE adds the following default persist method code to the servlet:
public void persist(Object object) {
try {
Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
utx.begin();
EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
em.persist(object);
utx.commit();
} catch(Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE,"exception caught", e);
throw new RuntimeException(e);
}
}
This code looks up the persistence unit defined by @PersistenceContext and an instance of the entity manager.
- In CustomerDetails.java, modify the generated persist method shown above to refer to our entity object.
When you are finished, the modified code should look like the following
(the code shown in bold indicates the changed lines):
public Customer findByID(Integer customerNr) {
Customer customer = null;
try {
Context ctx = (Context) new javax.naming.InitialContext().lookup("java:comp/env");
utx.begin();
EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
customer = em.find(Customer.class, customerNr);
utx.commit();
} catch(Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE,"exception caught", e);
throw new RuntimeException(e);
}
return customer;
}
- Uncomment the code in the processRequest method and add the following code in bold:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CustomerDetails</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Search Customer Information</h1>");
String customerNr = request.getParameter("customer_nr");
if((customerNr != null) && !(customerNr.equals(""))) {
Customer customer = findByID(new Integer(customerNr));
if(customer != null){
out.println("Customer's info for nr. " + customerNr + ": " + customer.getName());
}else{
out.println("Customer not found.");
}
}
out.println("<form>");
out.println("Customer number: <input type='text' name='customer_nr' />");
out.println("<input type=submit value=Select />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
- Press Ctrl-Shift-I to generate any missing import statements.
(The servlet requires an import statement for the Customer entity class.)
Running the Project
- In the Projects window, right-click the CustomerBook project node and choose Properties.
In the Run panel of the
Project Properties dialog box, type /CustomerDetails in the Relative URL field
and click OK.
- Right-click the project node and choose Run Project. The IDE starts the
application server, builds the project, and opens the CustomerDetails page in your browser.
- Enter an ID number (for example, "1") in the Customer number field and click Submit. The servlet shows you
the name of the customer with that ID number.
Summary
In this exercise, you built the CustomerBook application using Java EE 5 technology.
You then deployed the project and tested the web application.
See Also
For more information about using NetBeans IDE to develop Java EE applications, see the following resources:
To send comments and suggestions, get support, and keep informed on the latest
developments on the NetBeans IDE Java EE development features, join
the nbj2ee mailing list.