Java Reference
In-Depth Information
Food refreshedFood = inventory.getFood(foodName);
html.append("And after? " + refreshedFood);
} catch (NamingException e) {
html.append("We have no shop today. Try again tomorrow.");
You may be dismayed by how long this method is. In fact, almost all of it's concerned
with writing output to the page. The purchase itself could be managed in two or three
lines of code. Part of the reason that writing out the object states is so verbose is that
you have to retrieve the objects twice : once before the purchase and once after. If this
wasn't a database application, you'd expect that each food or customer instance was
unique. Changes to a food made in one part of the application (like the Shop ) would
automatically be reflected in food instances elsewhere.
Because this is a database, things aren't so easy. When they were passed to the Buy-
Food servlet, the food and customer instances moved outside the boundaries of the
persistence context and were detached . To see the latest state of the database after
changes, it's necessary to request new instances of the entity classes.
Let's play with the shop. If a new user named Holly buys two packs of Wensleydale
cheese, everything works exactly as you'd hope. The stock level of the cheese is decre-
mented, and the purchase price is added to your account (figure 3.14). The only dis-
appointing part is that you don't get the physical cheese to eat.
If Holly buys enough Wensleydale cheese, the stock levels will reduce to below the
blue cheese levels, and the front page special offer will suggest that customers buy
blue cheese instead.
What happens if Holly is more extravagant and buys three boxes of chocolates
instead? See figure 3.15.
Figure 3.14 When a user purchases a small quantity of cheese, their account is created and then deb-
ited, and the cheese stock levels are reduced.
Search WWH ::

Custom Search