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;
}
}