This is the second part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part two is gonna use the same example than Part 1, but now we’re going to work on a web environment.
Requirement
- Understand JPA concepts - If you have no idea what JPA is, please google it first
- Netbeans 6.8 and glassfish v3 installed
- MySQL database installed - If you have another one, make sure you have the JDBC driver
- Read Part 1 and have the database and POJO already created.
Creating the project within Netbeans
Let’s getting started through the project creation. Within Netbeans, go to File -> New Project -> Java Web -> Web Application. Choose a name, like JPAWebExample01 and Glassfish v3 as Server. On third screen, select JavaServer Faces and accept the default.

Note: don’t worry if you aren’t familiar with JSF. For this example we’ll focus on JPA only.
Creating the DataSource
Different than Stand-Alone application, in web application we could create a datasource to obtain and manage the database connection. This datasource lives in the Server, in our case, Glassfish.
Fortunately we can create it directly inside Netbeans in an easy way. Let’s do that now.
Similar than the post 1, let’s open the screen to create a entity class from the database. To do that, right mouse click on the project name and go to New -> Other -> Persistence -> Entity Classes from Database. On the new screen, you’re gonna see the Data Source field. Click on it and select New Data Source.

On the JNDI Name, fill up the field with the value jdbc/MySQL_jpatutorial. Database Connection select the previous connection you’ve done in Part 1. Click OK and the DataSource will be created.
Creating the Model and persistence.xml
After you have created the datasource, you should see the table products listed. Now, you can follow exactly the same step from Part 1 to create the persistence.xml and the model.
Creating a Manged-Bean
Our application uses JSF 2.0 and because of this we can create a Managed Bean to handle the requests coming from view. If you don’t know what Managed Bean is, think he is a Java class that handles requests from view. It is similar a Controller from MVC, but it is directly binding with the view.
In our example, the ManagedBean will obtain the EntityManager and call the NamedQuery.
To create a ManagedBean with Netbeans, follow the following steps:
Right mouse click on the project’s name New -> Other -> JavaServer Faces -> JSF Managed Bean. In the Class Name put JPATutorialBean and the Package put mbeans.

In th JPATutorialBean.java, let’s add a method called listAllProducts. The content looks like:
package mbeans; import entities.Products; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @ManagedBean(name="jpaTutorialBean") @RequestScoped public class JPATutorialBean { @PersistenceContext private EntityManager em; public void listAllProducts() { List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList(); for (Products product : listProducts) { System.out.println("Product: " + product.getDescription()); System.out.println("Price: " + product.getPrice()); System.out.println("---------------------------------------"); } } }
The method listAllProducts has no mistery. It is similar than the first post. Simply create a named query and prints out the result. However, pay attention on the lines:
@PersistenceContext
private EntityManager em;We’ve used an annotation called @PersistenceContext. Different than StandAlone application, where we had to obtain a EntityManagerFactory and after that create the EntityManager, in a web based application, the container is responsible to inject the EntityManager for us. Really simple, doesn’t it?
Editing the index.xhtml
How can we call the method listAllProducts from ManagedBean? We can do that editing the index.xhtml and creating a link to access this method. Edit the current index.xhtml and add the following:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<h:form>
<h:commandLink action="#{jpaTutorialBean.listAllProducts}">
<h:outputText value="List All Products" />
</h:commandLink>
</h:form>
</h:body>
</html>The code above is HTML and JSF stuff. Look at the h:commandLink and you’re gonna see where we bind the link with the method. JSF also makes our life easier.
Running and Testing the code
Now all changes are done, right mouse click on the project and select the Run option. A new page is gonna be opened in your browser and then click on the link.
Look at Netbeans console and you should see an output like below:
INFO: Product: product 1 INFO: Price: 100.0 INFO: --------------------------------------- INFO: Product: product 2 INFO: Price: 200.0 INFO: --------------------------------------- INFO: Product: product 3 INFO: Price: 200.5 INFO: ---------------------------------------
Conclusion
Doesn’t matter if you’re in a standalone or web application, the model (entity) is gonna be the same and the code to handle the JPA also, the biggest diffrence is the way to obtain the EntityManager. In a web application, the container is responsible to inject the EntityManager for us.
In the next topic we’re going talk about the strategies to retrieve values from JPA, such as: NamedQuery (already used), JPAQL and the newest feature, Criteria.
If you have any comment or question about this post, fell free to leave your message below.




VirtualMachine is a reality nowadays. If you have a base operating system (called host) and want to use another one on the base (called guest), you can use a VM to do that.



JSF 2.0 specification has already been approved, however its official version is gonna be released with JEE 6.
Se você, assim como eu, utiliza dual-boot em sua máquina (provavelmente Linux e Windows) certamente deve usar o 
One of the most interesting feature from JEE is the security behavior. If you’re using JEE, you do not need to worry about authentication and authorization, there is a security specification that talks about this issue.






Brazilian guy, IT Specialist, Linux User, IBM Certified SOA Fundamentals, Rational Developer, Sun Certified Java Associate 1.0, Sun Certified Java Programmer 1.4, Sun Certified Web Component Developer 1.4 and Sun Certified Business Component Developer 5. Also Ruby and Python enthusiastic.