10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Accessing Databases fromWeb Applications<br />

706<br />

As shown in the preceding code, an EntityManager instance is injected into an object using the<br />

@PersistenceContext annotation. An EntityManager instance is associated with a persistence<br />

context, which is a set of entity instances that the entity manager is tasked with managing.<br />

<strong>The</strong> annotation may specify the name of the persistence unit with which it is associated. This<br />

name must match a persistence unit defined in the application’s persistence.xml file.<br />

<strong>The</strong> next section explains how the BookDBAO object uses the entity manager instance to query<br />

the database.<br />

Accessing Data from the Database<br />

After the BookDBAO object obtains an EntityManager instance, it can access data from the<br />

database. <strong>The</strong> getBooks method of BookDBAO calls the createQuery method of the<br />

EntityManager instance to retrieve a list of all books by bookId:<br />

public List getBooks() throws BooksNotFoundException {<br />

try {<br />

return em.createQuery(<br />

"SELECT bd FROM Book bd ORDER BY bd.bookId").<br />

getResultList();<br />

} catch(Exception ex){<br />

throw new BooksNotFoundException("Could not get books: "<br />

+ ex.getMessage());<br />

}<br />

}<br />

<strong>The</strong> getBook method of BookDBAO uses the find method of the EntityManager instance to<br />

search the database for a particular book and return the associated Book instance:<br />

public Book getBook(String bookId) throws BookNotFoundException {<br />

Book requestedBook = em.find(Book.class, bookId);<br />

if (requestedBook == null) {<br />

throw new BookNotFoundException("Couldn’t find book: "<br />

+ bookId);<br />

}<br />

return requestedBook;<br />

}<br />

<strong>The</strong> next section describes how Duke’s Bookstore performs updates to the data.<br />

Updating Data in the Database<br />

In the Duke’s Bookstore application, updates to the database involve decrementing the<br />

inventory count of a book when the user buys copies of the book. <strong>The</strong> BookDBAO performs this<br />

update in the buyBooks and buyBook methods:<br />

<strong>The</strong> <strong>Java</strong> <strong>EE</strong> 5<strong>Tutorial</strong> • June 2010

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!