@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); } }
// 设置参数中的每一个BookSaleRecord的book属性 private void setBook(Collection<BookSaleRecord> brs) { for (BookSaleRecord br : brs) { // 调书本的数据访问层接口 Book book = bookDao.find(br.getBOOK_ID_FK()); br.setBook(book); } }