// 设置参数中的每一个BookSaleRecord的book属性 private void setBook(Collection<BookSaleRecord> brs) { for (BookSaleRecord br : brs) { // 调书本的数据访问层接口 Book book = bookDao.find(br.getBOOK_ID_FK()); br.setBook(book); } }
// 获取一次交易中所有书本的交易量 private int getAmount(Collection<BookSaleRecord> brs) { int result = 0; // 遍历书的交易记录,计算总价 for (BookSaleRecord br : brs) { result += Integer.valueOf(br.getTRADE_SUM()); } return result; }
// 获取一次交易中所有书本的名字, 以逗号隔开 private String getBookNames(Collection<BookSaleRecord> brs) { if (brs.size() == 0) return ""; StringBuffer result = new StringBuffer(); for (BookSaleRecord br : brs) { Book book = br.getBook(); result.append(book.getBOOK_NAME() + ", "); } // 去掉最后的逗号并返回 return result.substring(0, result.lastIndexOf(",")); }
// 获取一次交易中涉及的总价 private double getTotalPrice(Collection<BookSaleRecord> brs) { double result = 0; for (BookSaleRecord br : brs) { // 书本的交易量 int tradeSum = Integer.valueOf(br.getTRADE_SUM()); // 书的单价 double bookPrice = Double.valueOf(br.getBook().getBOOK_PRICE()); result += (bookPrice * tradeSum); } return result; }
@Override public void saveRecord(SaleRecord record) { // 遍历判断书的库存是否不够 for (BookSaleRecord r : record.getBookSaleRecords()) { String bookId = r.getBook().getID(); Book b = bookDao.find(bookId); // 当存库不够时,抛出异常 if (Integer.valueOf(r.getTRADE_SUM()) > Integer.valueOf(b.getREPERTORY_SIZE())) { throw new BusinessException(b.getBOOK_NAME() + " 的库存不够"); } } // 先保存交易记录 String id = saleRecordDao.save(record); // 再保存书的交易记录 for (BookSaleRecord r : record.getBookSaleRecords()) { // 设置销售记录id r.setT_SALE_RECORD_ID_FK(id); bookSaleRecordDao.saveBookSaleRecord(r); // 修改书的库存 String bookId = r.getBook().getID(); Book b = bookDao.find(bookId); // 计算剩余的库存 int leave = Integer.valueOf(b.getREPERTORY_SIZE()) - Integer.valueOf(r.getTRADE_SUM()); // 设置库存并将库存数保存到数据库 b.setREPERTORY_SIZE(String.valueOf(leave)); bookDao.updateRepertory(b); } }