background image

The Database Access Class

<< Accessing Databases | Initializing a Servlet >>
<< Accessing Databases | Initializing a Servlet >>

The Database Access Class

accessed through the database access class
tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/database/BookDBAO.
For example, ReceiptServlet invokes the BookDBAO.buyBooks method to update the book
inventory when a user makes a purchase. The buyBooks method invokes buyBook for each book
contained in the shopping cart, as shown in the following code.
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());
}
}
Sharing Information
The Java EE 5 Tutorial · September 2007
108