background image

EntityManager Instance

<< Accessing Data from the Database | rollback Method >>
<< Accessing Data from the Database | rollback Method >>

EntityManager Instance

public void buyBooks(ShoppingCart cart) throws OrderException{
Collection items = cart.getItems();
Iterator i = items.iterator();
try {
while (i.hasNext()) {
ShoppingCartItem sci = (ShoppingCartItem)i.next();
Book bd = (Book)sci.getItem();
String id = bd.getBookId();
int quantity = sci.getQuantity();
buyBook(id, quantity);
}
} catch (Exception ex) {
throw new OrderException(
"Commit failed: "
+ ex.getMessage());
}
}
public void buyBook(String bookId, int quantity)
throws OrderException {
try {
Book requestedBook = em.find(Book.class, bookId);
if (requestedBook != null) {
int inventory = requestedBook.getInventory();
if ((inventory - quantity) >= 0) {
int newInventory = inventory - quantity;
requestedBook.setInventory(newInventory);
} else{
throw new OrderException(
"Not enough of "
+ bookId +
" in stock to complete order.");
}
}
} catch (Exception ex) {
throw new OrderException(
"Couldn't purchase book: "
+ bookId + ex.getMessage());
}
}
In the buyBook method, the find method of the EntityManager instance retrieves one of the
books that is in the shopping cart. The buyBook method then updates the inventory on the Book
object.
To ensure that the update is processed in its entirety, the call to buyBooks is wrapped in a single
transaction. In the JSP versions of Duke's Bookstore, the Dispatcher servlet calls buyBooks and
therefore sets the transaction demarcations.
In the following code, the UserTransaction resource is injected into the Dispatcher servlet.
UserTransaction
is an interface to the underlying JTA transaction manager used to begin a
new transaction and end a transaction. After getting the UserTransaction resource, the servlet
calls to the begin and commit methods of UserTransaction to mark the boundaries of the
Accessing Databases from Web Applications
Chapter 25 · Persistence in the Web Tier
709