Next, the method does a JNDI lookup to obtain an instance of javax.persistence.
EntityManager . This class contains a number of methods to interact with the
database. Notice that the JNDI name used to obtain an EntityManager matches the
value of the name attribute of the @PersistenceContext annotation.
Once an instance of EntityManager is obtained from the JNDI lookup, we persist
our entity's properties by simply invoking the persist() method on it, passing
the entity as a parameter to this method. At this point, the data in our JPA entity is
inserted into the database.
In order for our database insert to take effect, we must commit our transaction,
which is done by invoking utx.commit() .
It is always a good idea to look for exceptions when dealing with JPA code. The
generated method does this, and if an exception is caught, it is logged and a
RuntimeException is thrown. Throwing a RuntimeException has the effect of
rolling back our transaction automatically, while letting the invoking code know
that something went wrong in our method. The UserTransaction class has a
rollback() method that we can use to roll back our transaction without having to
throw a RunTimeException .
At this point we have all the code we need to persist our entity's properties in the
database. Now we need to write some additional code for the user interface part of
our application. NetBeans can generate a rudimentary JSF page that will help us with
Generating the User Interface
To have NetBeans automatically generate the user interface, first we need to create a
new JSP as usual, by right-clicking on the project, selecting New | JSP , then entering
a name for our JSP in the New JSP File wizard. At this point, the generated markup
for the new JSP will look like this:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html;