JPA 2 and Netbeans Guide - Part 2 - JPA in a web environment

February 28th, 2010  | Tags: , , , ,

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.

  1. vignesh
    May 25th, 2010 at 09:30
    #1

    how can check junit for webapplication using JPA . can u provide me an example for checking junit test ?

  2. May 25th, 2010 at 09:57
    #2

    If you want to use JUnit + JPA, I advice you to use a mock framework, such as EasyMock, to mock the EntityManager or anything else. The rest of the process is the same.
    I wrote a post about Mock a long time ago. Please, take a look at the blog and probably you’re going to find it out.

  3. Osho Ilamah
    June 5th, 2010 at 07:23
    #3

    Jair, thank you for your clear and straight forward explanation. I have always been confused on how to get the EntityManager in an enterprise app.

    You have shown an example with a “find” query. This does not require transactions as there is no entity mutation. It would have been nice if you mentioned the difference between resource level transactions and JTA transactions as this is another area where JPA in an enterprise app could differ from JPA on a stand alone (J2SE) app.

    However, I remeber reading somewhere that creating an EntityManagerFactory is

  4. ioannis
    June 7th, 2010 at 03:15
    #4

    Dear Sir

    Could you explain how we can setup Netbeans 6.8 to explicitly utilize JPA 2 and not JPA 1. Our implementation supports JPA 1 and not JPA 2. Is there a config setting somewhere in Netbeans?

TOP