@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 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(",")); }