QueryWrapper queryWrapper = new QueryWrapper<>();queryWrapper.eq("age", 20);List list = userInfoMapper.selectList(queryWrapper );123
以上就是查询用户表,用户年龄等于20的用户信息
# 条件查询(QueryWrapper lambda)
QueryWrapper queryWrapper = new QueryWrapper<>();queryWrapper.lambda().eq(UserInfo::getAge, 20);List list = userInfoMapper.selectList(queryWrapper );123
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(UserInfo::getAge, 20);List list = userInfoMapper.selectList(queryWrapper );123
LambdaQueryWrapper 与 QueryWrapper 的 lambda 写法基本一致
# 分页查询
// 条件查询LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(UserInfo::getAge, 20);// 分页对象Page queryPage = new Page<>(page, limit);// 分页查询IPage iPage = userInfoMapper.selectPage(queryPage , queryWrapper);// 数据总数Long total = iPage.getTotal();// 集合数据Listlist = iPage.getRecords();1234567891011
以上就是分页查询,如果无需条件查询,queryWrapper 可为 null
# 分页查询(联表)
当我们需要关联表格分页查询时,第3步已经满足不了我们的需求了,那么我们需要进行联表分页查询
假设我们需要的 SQL 语句如下:
SELECT a.*, b.`name`AS sex_text FROM user_info aLEFTJOIN user_sex b ON ( a.sex = b.id ) WHERE1 = 1AND a.age > 20123456789
<select id="list" resultType="com.zyxx.vo.UserInfoVO"> SELECT a.*, b.`name` AS sex_text FROM user_info a LEFT JOIN user_sex b ON ( a.sex = b.id ) ${ew.customSqlSegment}select>123456789
4、UserInfoServiceImpl.java 中
// 条件查询LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(UserInfo::getAge, 20);// 分页对象Page queryPage = new Page<>(page, limit);// 分页查询IPage iPage = userInfoMapper.list(queryPage , queryWrapper);// 数据总数Long total = iPage.getTotal();// 用户数据Listlist = iPage.getRecords();1234567891011
以上就是分页查询(联表)时的操作,这个应该是用的比较多的
# AND 和 OR
queryWrapper 默认是按照 and 来连接的,但是在我们业务需求中,肯定会用到 or 来写 SQL
1、初级
假设我们需要的 SQL 语句如下:
SELECT a.* FROM user_info a WHERE1 = 1AND a.id <> 1AND ( a.`name` = 'jack'OR a.phone = '13888888888' )12345678
那么我们可以这样写:
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();// AND a.id <> 1 queryWrapper.ne(UserInfo::getId, "1");// AND ( a.`name` = 'jack' OR a.phone = '13888888888' )queryWrapper.and(i -> i.eq(UserInfo::getName, "jack").or().eq(UserInfo::getPhone, "13888888888"));// 查询结果Listlist = userInfoMapper.selectList(queryWrapper);1234567
以上就完成了初级的 and 和 or 联用的情况
2、复杂
假设我们需要的 SQL 语句如下:
SELECT a.* FROM user_info a WHERE1 = 1AND a.id <> 1AND ( (a.`name` = 'jack'AND a.category = 1) OR (a.phone = '13888888888'OR a.category = 2) )12345678
那么我们可以这样写:
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();// AND a.id <> 1queryWrapper.ne(UserInfo::getId, "1");// AND ( (a.`name` = 'jack' AND a.category = 1) OR (a.phone = '13888888888' OR a.category = 2) )queryWrapper.and(i -> (i.and(j -> j.eq(UserInfo::getName, "jack").eq(UserInfo::getCategory, 1))).or(j -> j.eq(UserInfo::getPhone, "13888888888").eq(UserInfo::getCategory, 2)));// 查询结果List list = userInfoMapper.selectList(queryWrapper);1234567