@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); } }
// 获取一次交易中所有书本的交易量 private int getAmount(Collection<BookSaleRecord> brs) { int result = 0; // 遍历书的交易记录,计算总价 for (BookSaleRecord br : brs) { result += Integer.valueOf(br.getTRADE_SUM()); } return result; }
// 获取一次交易中涉及的总价 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; }