1、新增和更新时的公用查重方法
封装对象新增和更新时的公用查重方法。
/**
* 校验唯一性
*
* @param student 学生信息
*/
private void checkUnique(Student student) {
boolean exists = baseMapper.exists(Wrappers.<Student>lambdaQuery()
.ne(Student.getId() != null, Student::getId, student.getId()) // 先进行主键过滤,唯一性强过滤范围大,走索引较快
.eq(Student::getName, student.getName()));
if (exists) {
throw new RuntimeException("姓名已存在");
}
}
2、只判断数据是否存在,后续不使用查询对象时,使用 exist。
boolean exists = baseMapper.exists(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName()));
if (exists) {
throw new RuntimeException("姓名已存在");
}
3、判断数据是否存在,后续需要使用查询对象时,使用 selectOne。
Student student = baseMapper.selectOne(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName())
.last("limit 1")); // 限制1条,防止数据库数据异常重复时抛出异常
if (student != null) {
throw new RuntimeException("姓名已存在:" + student.getName());
}
3、判断数据是否存在,需要获取重复数量时,使用 selectCount。
long count = baseMapper.selectCount(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName()));
if (count > 0) {
throw new RuntimeException("姓名已存在:" + count + "个");
}