background image

ContextListener Class

<< Obtaining Access to an Entity Manager | Accessing Data from the Database >>
<< Obtaining Access to an Entity Manager | Accessing Data from the Database >>

ContextListener Class

public final class ContextListener implements SerlvetContextListener {
...
@PersistenceUnit
private EntityManagerFactory emf;
public void contextInitialized(ServletContexEvent event) {
context = event.getServletContext();
...
try {
BookDBAO bookDB = new BookDBAO(emf);
context.setAttribute(
"bookDB", bookDB);
} catch (Exception ex) {
System.out.println(
"Couldn't create bookstore database bean: "
+ ex.getMessage());
}
}
}
The BookDBAO object can then obtain an EntityManager from the EntityManagerFactory that
the ContextListener object passes to it:
private EntityManager em;
public BookDBAO (EntityManagerFactory emf) throws Exception {
em = emf.getEntityManager();
...
}
The JavaServer Faces version of Duke's Bookstore gets access to the EntityManager instance a
little differently. Because managed beans allow resource injection, you can inject the
EntityManagerFactory
instance into BookDBAO.
In fact, you can bypass injecting EntityManagerFactory and instead inject the EntityManager
directly into BookDBAO. This is because thread safety is not an issue with request-scoped beans.
Conversely, developers need to be concerned with thread safety when working with servlets and
listeners. Therefore, a servlet or listener needs to inject an EntityManagerFactory instance,
which is thread-safe, whereas a persistence context is not thread-safe. The following code shows
part of the BookDBAO object included in the JavaServer Faces version of Duke's Bookstore:
import javax.ejb.*;
import javax.persistence.*;
import javax.transaction.NotSupportedException;
public class BookDBAO {
@PersistenceContext
private EntityManager em;
...
Accessing Databases from Web Applications
Chapter 25 · Persistence in the Web Tier
707