单表操作删除时,默认框架已提供了,但有时候需要根据条件判断是否允许删除;如,客户表,如果客户信息已被使用,而不允许被删除。
方法同数据唯一性验证,查询关联表是否有引用记录,并统计数量,大于 0,则不允许删除。
CustomerDao.xml 中增加查询方法
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jeesite.modules.customer.dao.CustomerDao"> <!-- 查询数据 <select id="findList" resultType="Customer"> SELECT ${sqlMap.column.toSql()} FROM ${sqlMap.table.toSql()} <where> ${sqlMap.where.toSql()} </where> ORDER BY ${sqlMap.order.toSql()} </select> --> <select id="getOrderReviewNum" resultType="Long"> SELECT count(0) FROM `product_order_review` a where a.status =0 AND a.customer_code = #{customerCode} LIMIT 1 </select> <select id="getOrderNum" resultType="Long"> SELECT count(0) FROM `product_work_order` a where a.status =0 AND a.customer_code = #{customerCode} LIMIT 1 </select> <select id="getTransportNum" resultType="Long"> SELECT count(0) FROM `product_transport` a where a.customer_code = #{customerCode} LIMIT 1 </select> </mapper>
CustomerDao.java 文件中,增加
Long getOrderReviewNum(String customerCode); Long getOrderNum(String customerCode); Long getTransportNum(String customerCode);
CustomerService.java 中增加及调整 delete 方法
@Autowired private CustomerDao customerDao; /** * 删除数据 * * @param customer */ @Override @Transactional public void delete(Customer customer) { if (checkCustomerIsUse(customer.getCustomerCode())) { throw new RuntimeException("客户已被使用,不能被删除"); } super.delete(customer); } public Long getOrderReviewNum(String customerCode) { return customerDao.getOrderReviewNum(customerCode); } public Long getOrderNum(String customerCode) { return customerDao.getOrderNum(customerCode); } public Long getTransportNum(String customerCode) { return customerDao.getTransportNum(customerCode); } public boolean checkCustomerIsUse(String customerCode) { if (getOrderReviewNum(customerCode) > 0) return true; if (getOrderNum(customerCode) > 0) return true; if (getTransportNum(customerCode) > 0) return true; return false; }
CustomerController.java 控制器中,调整 delete 方法
/** * 删除数据 */ @RequiresPermissions("customer:customer:edit") @RequestMapping(value = "delete") @ResponseBody public String delete(Customer customer) { try { customerService.delete(customer); return renderResult(Global.TRUE, text("删除客户信息成功!")); } catch (RuntimeException e) { return renderResult(Global.FALSE, text(e.getMessage())); } }