25.5.2 开发业务逻辑处理类
在bookshop应用中,将要在"bookshop/bookshop"目录下创建以下的Java类:
BookDetail.java
Order.java
ShopCar.java
ShopCarItem.java
BookDB.java
1.BookDetail.java、Order.java
BookDetail.java类是一个实体类,主要是表示书籍的信息,与数据库表book相对应。在BookDetail.java类中,主要的方法是get和set方法,其具体代码实现如下所示:
package bookshop;
import java.util.Date;
public class BookDetail implements Comparable {
private String bookId="";
private String title="";
private String name="";
private Date time;
private String info="";
private String pie="";
private double price=0;
private int saleAmount=0;
public BookDetail(String bookId,String title,String name,
Date time,String info,String pie,double price,int saleAmount){
this.bookId=bookId;
this.title=title;
this.name=name;
this.time=time;
this.info=info;
this.pie=pie;
this.price=price;
this.saleAmount=saleAmount;
}
public String getBookId() {
return bookId;
}
public String getInfo() {
return info;
}
public String getName() {
return name;
}
public String getPie() {
return pie;
}
public double getPrice() {
return price;
}
public int getSaleAmount() {
return saleAmount;
}
public Date getTime() {
return time;
}
public String getTitle() {
return title;
}
public void setBookId(String string) {
bookId = string;
}
public void setInfo(String string) {
info = string;
}
public void setName(String string) {
name = string;
}
public void setPie(String string) {
pie = string;
}
public void setPrice(double d) {
price = d;
}
public void setSaleAmount(int d) {
saleAmount = d;
}
public void setTime(Date date) {
time = date;
}
public void setTitle(String string) {
title = string;
}
public int compareTo(Object o) {
BookDetail bd = (BookDetail)o;
int lastCmp = title.compareTo(bd.title);
return (lastCmp);
}
}
Order.java类是一个实体类,主要是表示订单的信息,与数据库表orderList相对应。在Order.java类中,主要的方法是get和set方法,其具体代码实现如下所示:
package bookshop;
import java.io.Serializable;
import java.util.Date;
public class Order implements Serializable{
private String orderID="";
private String status="";
private Date time;
private int allAmount=0;
private double allMoney=0;
private String name="";
private String phone="";
private String code="";
private String info="";
private String Address="";
public Order (){
}
public Order (String orderID,String status, Date time, int allAmount,
double allMoney,String name,String phone,String code,String info){
this.orderID=orderID;
this.status=status;
this.time=time;
this.allAmount=allAmount;
this.allMoney=allMoney;
this.name=name;
this.phone=phone;
this.code=code;
this.info=info;
}
public int getAllAmount() {
return allAmount;
}
public void setAllAmount(int allAmount) {
this.allAmount = allAmount;
}
public double getAllMoney() {
return allMoney;
}
public void setAllMoney(double allMoney) {
this.allMoney = allMoney;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
2.ShopCar.java、ShopCarItem.java
ShopCar.java和ShopCarItem.java类实现了网上书店的购物车部分功能,分别代表购物车和购物车中的书籍条目。在一个购物车中,可以包含多个购物车书籍条目,购物车书籍条目代表了用户需要购买的书籍信息、数量及金额等信息。
例如,某个用户的购物车放置了两种书籍:一种是编号为IS00000001的《Java》书籍2本;另一种是编号为IS00000004的《Delphi》书籍1套。那么在ShopCar对象中就包含了两个ShopCarItem对象。ShopCarItem包含两个成员变量:Object item和int quantity,其中Object item代表购买书籍的详细信息,它引用了前面建立的ShopCarItem对象;int quantity代表购买书籍的数量。ShopCar、ShopCarItem与BookDetail三个对象之间的关系可以用图25-7表示:
图25-7 ShopCar、ShopCarItem与BookDetail对象的关系
ShopCarItem.java类主要是实现了get、set方法和增、减书籍数量的方法,代码如下所示:
package bookshop;
public class ShopCarItem {
Object item;
int quantity;
public ShopCarItem(Object anItem) {
item = anItem;
quantity = 1;
}
public void incrementQuantity() {
quantity++;
}
public void decrementQuantity() {
quantity--;
}
public Object getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
}
ShopCar.java类主要是实现了购物车功能。其add方法是实现往购物车中放置书籍,remove方法是实现从购物车中删除已选择的书籍,getTotal方法是计算购物车中书籍的总金额。其代码实现如下所示:
package bookshop;
import java.util.*;
public class ShopCar {
HashMap items = null;
int numberOfItems = 0;
public ShopCar() {
items = new HashMap();
}
public synchronized void add(String bookId, BookDetail book) {
if(items.containsKey(bookId)) {
ShopCarItem scitem = (ShopCarItem) items.get(bookId);
scitem.incrementQuantity();
} else {
ShopCarItem newItem = new ShopCarItem(book);
items.put(bookId, newItem);
}
numberOfItems++;
}
public synchronized void remove(String bookId) {
if(items.containsKey(bookId)) {
ShopCarItem scitem = (ShopCarItem) items.get(bookId);
scitem.decrementQuantity();
if(scitem.getQuantity() <= 0)
items.remove(bookId);
numberOfItems--;
}
}
public synchronized Collection getItems() {
return items.values();
}
protected void finalize() throws Throwable {
items.clear();
}
public synchronized int getNumberOfItems() {
return numberOfItems;
}
public synchronized double getTotal() {
double amount = 0.0;
for(Iterator i = getItems()。iterator(); i.hasNext(); ) {
ShopCarItem item = (ShopCarItem) i.next();
BookDetail bookDetails = (BookDetail) item.getItem();
amount += item.getQuantity() * bookDetails.getPrice();
}
return roundOff(amount);
}
private double roundOff(double x) {
ong val = Math.round(x*100);
return val/100.0;
}
public synchronized void clear() {
items.clear();
numberOfItems = 0;
}
}
3.BookDB.java
该网上书店系统是使用JDBC访问MS Access数据库。它是通过JDBC-ODBC驱动类型链接数据库,所以需要先建立ODBC数据源。建立ODBC数据源的方法可以参考第9章第3节的介绍,在这里ODBC数据源的名称为BookShopDB.
BookDB.java类主要是对数据库的访问操作类,包括数据库链接、断开数据库链接、查询数据库纪录和修改数据库纪录等方法。在BookDB.java类里实现了以下方法:getConnection方法实现数据库链接;getBookDetail方法实现读取书籍列表的详细信息;buyBooks方法实现购买书籍;order方法实现了下订单的处理。其代码实现主要部分如下所示:
package bookshop;
import java.sql.*;
import java.util.*;
public class BookDB {
private ArrayList alBooks;
private String dbUrl="jdbc:odbc:BookShopDB";
private String orderId;
public BookDB () throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
public Connection getConnection()throws Exception{
return java.sql.DriverManager.getConnection(dbUrl);
}
public void closeConnection(Connection con){
try{
if(con!=null) con.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void closePrepStmt(PreparedStatement prepStmt){
try{
if(prepStmt!=null) prepStmt.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void closeResultSet(ResultSet rs){
try{
if(rs!=null) rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
public int getNumberOfBooks() throws Exception {
Connection con=null;
PreparedStatement prepStmt=null;
ResultSet rs=null;
alBooks = new ArrayList();
try {
con=getConnection();
String strSql = "select * " + "from book";
prepStmt = con.prepareStatement(strSql);
rs = prepStmt.executeQuery();
while (rs.next()) {
BookDetail bd = new BookDetail(rs.getString("bookID"), rs.getString("title"),
rs.getString("name"),rs.getDate("time"), rs.getString("info"),
rs.getString("pie"),rs.getDouble("price"),rs.getInt("saleAmount"));
alBooks.add(bd);
}
}finally{
closeResultSet(rs);
closePrepStmt(prepStmt);
closeConnection(con);
}
return alBooks.size();
}
public Collection getBookList()throws Exception{
Connection con=null;
PreparedStatement prepStmt=null;
ResultSet rs =null;
alBooks = new ArrayList();
try {
con=getConnection();
String strSql = "select * " + "from book order by bookID";
prepStmt = con.prepareStatement(strSql);
rs = prepStmt.executeQuery();
while (rs.next()) {
BookDetail bd = new BookDetail(rs.getString("bookID"), rs.getString("title"),
rs.getString("name"),rs.getDate("time"), rs.getString("info"),
rs.getString("pie"),rs.getDouble("price"),rs.getInt("saleAmount"));
alBooks.add(bd);
}
}finally{
closeResultSet(rs);
closePrepStmt(prepStmt);
closeConnection(con);
}
Collections.sort(alBooks);
return alBooks;
}
public BookDetail getBookDetail(String bookId) throws Exception {
Connection con=null;
PreparedStatement prepStmt=null;
ResultSet rs =null;
try {
con=getConnection();
System.out.println("getConnection");
String strSql = "select * from book where bookID = ? ";
prepStmt = con.prepareStatement(strSql);
prepStmt.setString(1, bookId);
rs = prepStmt.executeQuery();
if (rs.next()) {
BookDetail bd = new BookDetail(rs.getString("bookID"), rs.getString("title"),
rs.getString("name"),rs.getDate("time"), rs.getString("info"),
rs.getString("pie"),rs.getDouble("price"),rs.getInt("saleAmount"));
prepStmt.close();
return bd;
}
else {
return null;
}
}finally{
closeResultSet(rs);
closePrepStmt(prepStmt);
closeConnection(con);
}
}
public void buyBooks(ShopCar car)throws Exception {
Connection con=null;
Collection items = car.getItems();
Iterator i = items.iterator();
try {
con=getConnection();
con.setAutoCommit(false);
while (i.hasNext()) {
ShopCarItem sci = (ShopCarItem)i.next();
BookDetail bd = (BookDetail)sci.getItem();
String bookId=bd.getBookId();
int quantity = sci.getQuantity();
buyBook(bookId, quantity,con);
orderDetail(bd, quantity,con);
}
con.commit();
con.setAutoCommit(true);
} catch (Exception ex) {
con.rollback();
throw ex;
}finally{
closeConnection(con);
}
}
public void buyBook(String bookId, int quantity,Connection con) throws Exception {
PreparedStatement prepStmt=null;
ResultSet rs=null;
try{
String strSql = "select * " + "from book where bookID = ? ";
prepStmt = con.prepareStatement(strSql);
prepStmt.setString(1, bookId);
rs = prepStmt.executeQuery();
if (rs.next()) {
prepStmt.close();
strSql ="update book set saleamount = saleamount + ? where bookID = ?";
prepStmt = con.prepareStatement(strSql);
prepStmt.setInt(1, quantity);
prepStmt.setString(2, bookId);
prepStmt.executeUpdate();
prepStmt.close();
}
}finally{
closeResultSet(rs);
closePrepStmt(prepStmt);
}
}
public void orderDetail(BookDetail bd, int quantity,Connection con) throws Exception {
PreparedStatement prepStmt=null;
try{
String strSql ="insert into orderDetail(orderID,bookId,price,amount,moneys)" +
" values(?,?,?,?,?)";
prepStmt = con.prepareStatement(strSql);
System.out.println(orderId);
prepStmt.setString(1,orderId);
prepStmt.setString(2, bd.getBookId());
prepStmt.setDouble(3, bd.getPrice());
prepStmt.setInt(4, quantity);
prepStmt.setDouble(5, bd.getPrice()*quantity);
prepStmt.executeUpdate();
prepStmt.close();
}finally{
closePrepStmt(prepStmt);
}
}
public void order(Order order) throws Exception{
Connection con=null;
PreparedStatement prepStmt=null;
try {
con=getConnection();
String strSql = "insert into orderList(orderID,status,allAmount,allMoney,name,phone,address,code,info) " +
" values(?,?,?,?,?,?,?,?,?)";
prepStmt = con.prepareStatement(strSql);
orderId=getNowTime();
order.setOrderID(orderId);
prepStmt.setString(1, orderId);
prepStmt.setString(2, "有效");
prepStmt.setInt(3, order.getAllAmount());
prepStmt.setDouble(4, order.getAllMoney());
prepStmt.setString(5, order.getName());
prepStmt.setString(6, order.getPhone());
prepStmt.setString(7, order.getAddress());
prepStmt.setString(8, order.getCode());
prepStmt.setString(9, order.getInfo());
prepStmt.executeUpdate();
}finally{
closePrepStmt(prepStmt);
closeConnection(con);
}
}
public static String getNowTime() {
java.util.Date ctime = new java.util.Date();
String rTime = "";
java.text.SimpleDateFormat cf = new java.text.SimpleDateFormat(
"yyyyMMddHHmmss");
rTime = cf.format(ctime);
return rTime;
}
}