background image

The transaction Tag

<< SQL Tag Library | query Tag Result Interface >>
<< SQL Tag Library | query Tag Result Interface >>

The transaction Tag

both tags to update the database inventory for each purchase. Because a shopping cart can
contain more than one book, the transaction tag is used to wrap multiple queries and updates.
First, the page establishes that there is sufficient inventory; then the updates are performed.
<c:set var=
"sufficientInventory" value="true" />
<sql:transaction>
<c:forEach var=
"item" items="${sessionScope.cart.items}">
<c:set var=
"book" value="${item.item}" />
<c:set var=
"bookId" value="${book.bookId}" />
<sql:query var=
"books"
sql=
"select * from PUBLIC.books where id = ?" >
<sql:param value=
"${bookId}" />
</sql:query>
<jsp:useBean id=
"inventory"
class=
"database.BookInventory" />
<c:forEach var=
"bookRow" begin="0"
items=
"${books.rowsByIndex}">
<jsp:useBean id=
"bookRow"
type=
"java.lang.Object[]" />
<jsp:setProperty name=
"inventory" property="quantity"
value=
"${bookRow[7]}" />
<c:if test=
"${item.quantity > inventory.quantity}">
<c:set var=
"sufficientInventory" value="false" />
<h3><font color=
"red" size="+2">
<fmt:message key=
"OrderError"/>
There is insufficient inventory for
<i>${bookRow[3]}</i>.</font></h3>
</c:if>
</c:forEach>
</c:forEach>
<c:if test=
"${sufficientInventory == 'true'}" />
<c:forEach var=
"item" items="${sessionScope.cart.items}">
<c:set var=
"book" value="${item.item}" />
<c:set var=
"bookId" value="${book.bookId}" />
<sql:query var=
"books"
sql=
"select * from PUBLIC.books where id = ?" >
<sql:param value=
"${bookId}" />
</sql:query>
<c:forEach var=
"bookRow" begin="0"
items=
"${books.rows}">
<sql:update var=
"books" sql="update PUBLIC.books set
inventory = inventory - ? where id = ?
" >
<sql:param value=
"${item.quantity}" />
<sql:param value=
"${bookId}" />
SQL Tag Library
Chapter 7 · JavaServer Pages Standard Tag Library
219