background image

Obtaining Access to an Entity Manager

<< Creating an Entity Class | ContextListener Class >>
<< Creating an Entity Class | ContextListener Class >>

Obtaining Access to an Entity Manager

}
public String getTitle() {
return this.title;
}
...
public void setBookId(String id) {
this.bookId=id;
}
public void setTitle(String title) {
this.title=title;
}
...
}
Obtaining Access to an Entity Manager
The BookDBAO object of the Duke's Bookstore application includes methods for getting the book
data from the database and updating the inventory in the database when books are sold. In
order to perform database queries, the BookDBAO object needs to obtain an EntityManager
instance.
The Java Persistence API allows developers to use annotations to identify a resource so that the
container can transparently inject it into an object. You can give an object access to an
EntityManager
instance by using the @PersistenceUnit annotation to inject an
EntityManagerFactory
, from which you can obtain an EntityManager instance.
Unfortunately for the web application developer, resource injection using annotations can only
be used with classes that are managed by a Java EE compliant container. Because the web
container does not manage JavaBeans components, you cannot inject resources into them. One
exception is a request-scoped JavaServer Faces managed bean. These beans are managed by the
container and therefore support resource injection. This is only helpful if your application is a
JavaServer Faces application.
You can still use resource injection in a web application that is not a JavaServer Faces
application if you can do it in an object that is managed by the container. These objects include
servlets and ServletContextListener objects. These objects can then give the application's
beans access to the resources.
In the case of Duke's Bookstore, the ContextListener object creates the BookDBAO object and
puts it into application scope. In the process, it passes to the BookDBAO object the
EntityManagerFactory
object that was injected into ContextListener:
Accessing Databases from Web Applications
The Java EE 5 Tutorial · September 2007
706