在日常开发中,最常用的是数据唯一验证;如客户名称不能重复。因为,自己水平有限,在 JeeSite 中暂未找到合适的方法。
这里介绍一种笨的方法,通过在 mybatis 中增加查询 SQL来实现:
如,在 CustomerDao.xml 文件增加 getByCustomerName:
<?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="getByCustomerName" resultType="Customer"> SELECT * FROM `basic_customer` a where a.customer_name = #{customerName} LIMIT 1 </select> </mapper>
在 CustomerDao.java 中增加:
Customer getByCustomerName(String customerName);
在服务层 CustomerService.java 中增加:
@Autowired private CustomerDao customerDao; public Customer getByCustomerName(String customerName) { return customerDao.getByCustomerName(customerName); } /** * 保存数据(插入或更新) * * @param customer */ @Override @Transactional public void save(Customer customer) { Customer tmp = getByCustomerName(customer.getCustomerName()); if (customer.getIsNewRecord()) { if (tmp != null) { throw new RuntimeException("客户名称已存在"); } } else { if (tmp != null && !tmp.getId().equals(customer.getId())) { throw new RuntimeException("客户名称已存在"); } } super.save(customer); }
在控制器层 CustomerController.java 中修改
/** * 保存数据 */ @RequiresPermissions("customer:customer:edit") @PostMapping(value = "save") @ResponseBody public String save(@Validated Customer customer) { try { customerService.save(customer); return renderResult(Global.TRUE, text("保存客户信息成功!")); } catch (RuntimeException e) { return renderResult(Global.FALSE, text(e.getMessage())); } }