background image

Accessing Data from the Database

<< ContextListener Class | EntityManager Instance >>
<< ContextListener Class | EntityManager Instance >>

Accessing Data from the Database

As shown in the preceding code, an EntityManager instance is injected into an object using the
@PersistenceContext
annotation. An EntityManager instance is associated with a persistence
context, which is a set of entity instances that the entity manager is tasked with managing.
The annotation may specify the name of the persistence unit with which it is associated. This
name must match a persistence unit defined in the application's persistence.xml file.
The next section explains how the BookDBAO object uses the entity manager instance to query
the database.
Accessing Data from the Database
After the BookDBAO object obtains an EntityManager instance, it can access data from the
database. The getBooks method of BookDBAO calls the createQuery method of the
EntityManager
instance to retrieve a list of all books by bookId:
public List getBooks() throws BooksNotFoundException {
try {
return em.createQuery(
"SELECT bd FROM Book bd ORDER BY bd.bookId").
getResultList();
} catch(Exception ex){
throw new BooksNotFoundException(
"Could not get books: "
+ ex.getMessage());
}
}
The getBook method of BookDBAO uses the find method of the EntityManager instance to
search the database for a particular book and return the associated Book instance:
public Book getBook(String bookId) throws BookNotFoundException {
Book requestedBook = em.find(Book.class, bookId);
if (requestedBook == null) {
throw new BookNotFoundException(
"Couldn't find book: "
+ bookId);
}
return requestedBook;
}
The next section describes how Duke's Bookstore performs updates to the data.
Updating Data in the Database
In the Duke's Bookstore application, updates to the database involve decrementing the
inventory count of a book when the user buys copies of the book. The BookDBAO performs this
update in the buyBooks and buyBook methods:
Accessing Databases from Web Applications
The Java EE 5 Tutorial · September 2007
708