文章目录
前言
针对大家数据查重方式写法的各异性,我在此给出不同场景下基于效率、空间、写法简单考虑的最优查重方法。
一、数据库查重场景
- 通常使用 baseMapper.selectOne 替换 baseMapper.exist,因为 selectOne 添加 “limit 1” 语句后查询速度比较快,且更节省内存空间。
1、新增和更新时的公共查重方法
/**
* 校验唯一性
*
* @param student 学生信息
*/
private void checkUnique(Student student) {
Student student = baseMapper.selectOne(Wrappers.<Student>lambdaQuery()
.ne(Student.getId() != null, Student::getId, student.getId()) // 存在主键时进行主键过滤
.eq(Student::getName, student.getName())
.last("limit 1")); // 1.提高查询效率。2.防止多条数据异常。(通常定义为常量)
if (student != null) {
throw new RuntimeException("姓名已存在");
}
}
2、只判断数据是否存在,使用 selectOne
Student student = baseMapper.selectOne(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName())
.last("limit 1")); // 1.提高查询效率。2.防止多条数据异常。(通常定义为常量)
if (student != null) {
throw new RuntimeException("姓名已存在:" + student.getName());
}
3、需要查询列表数据,使用 selectList
List<Student> studentList = baseMapper.selectList(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName()));
if (CollUtil.isNotEmpty(studentList)) {
throw new RuntimeException("姓名已存在");
}
4、需要查询重复数量时,使用 selectCount
long count = baseMapper.selectCount(Wrappers.<Student>lambdaQuery()
.eq(Student::getName, student.getName()));
if (count > 0) {
throw new RuntimeException("姓名已存在:" + count + "个");
}
二、集合查重场景
1、只判断数据是否存在,使用 stream().anyMatch
boolean exists = sysUserList.stream()
.anyMatch(x -> StrUtil.equals(x.getUsername(), "taibai"));
if (exists) {
throw new RuntimeException("姓名已存在");
}
2、判断数据是否存在,后续需要使用查询对象时,使用 stream().filter().findFirst
SysUser sysUser = sysUserList.stream()
.filter(x -> StrUtil.equals(x.getUsername(), "taibai"))
.findFirst().orElse(null);
if (sysUser != null) {
throw new RuntimeException("姓名已存在");
}
3、判断数据是否存在,需要获取重复数量时,使用 selectCount
SysUser sysUser = sysUserList.stream()
.filter(x -> StrUtil.equals(x.getUsername(), "taibai"))
.findFirst().orElse(null);
if (count > 0) {
throw new RuntimeException("姓名已存在:" + count + "个");
}