mybatis-plus自带QueryWrapper自定义sql实现复杂查询实例详解
作者:瑶山
常用写法
xxxDO=实体类, 相当于:
select name, id from xxx group by name where delete_flag = 0 and status = 0
LambdaQueryWrapper<xxxDO> queryWrapper = Wrappers.lambdaQuery(); queryWrapper.select(xxxDO::getName, DO::getId); queryWrapper.eq(xxxDO::getDeleteFlag, 0); queryWrapper.eq(xxxDO::getStatus, 0); queryWrapper.groupBy(xxxDO::getName); List<xxxDO> list = getBaseMapper().selectList(queryWrapper);
自定义sql
xxxDO=实体类,相当于:
select sex, ifnull(count(id), 0) AS num, CASE WHEN sex = 1 THEN '男' WHEN sex = 0 THEN '女' ELSE '未知' END AS sexStr from xxx group by sex where status = 0
LambdaQueryWrapper<xxxDO> queryWrapper = new QueryWrapper<xxxDO>() .select("sex, ifnull(count(id), 0) AS num, CASE WHEN sex = 1 THEN '男' WHEN sex = 0 THEN '女' ELSE '未知' END AS sexStr").lambda(); queryWrapper.eq(xxxDO::getStatus, 0); queryWrapper.groupBy(xxxDO::getSex); List<Map<String, Object>> mapList = getBaseMapper().selectMaps(queryWrapper); Map<String, String> registerNumMap = new HashMap<>(mapList.size()); for (Map<String, Object> map : mapList) { String key = String.valueOf(map.get("sexStr")); String num = String.valueOf(map.get("num")); registerNumMap.put(key, num); }
返回结果是一个list, 里面的map key是查询的属性名, value是参数值。伪代码示意:
list[0]
map[0] (sex=1)
map[1] (num=5)
map[2] (sexStr=男)
list[1]
map[0] (sex=1)
map[1] (num=5)
map[2] (sexStr=男)
偶然而发, 记录一下
补充: 查询条件中使用函数apply
queryWrapper.apply("INET_ATON(qsip) <= INET_ATON({0})", ipQuery); queryWrapper.apply("INET_ATON(zzip) >= INET_ATON({0})", ipQuery);
补充: 末尾sql追加last
queryWrapper.last(" order by id asc"); queryWrapper.last("limit 1");
补充:排序
// last也可以追加limit 这里用page接口 IPage<Entity> buildPage = new Page<>(0, 200); // ServiceImpl的page调用的是baseMapper的selectPage, getBaseMapper().selectPage() IPage<Entity> page = page(buildPage, queryWrapper);
sql打印
补充:Mybatis-Plus QueryWrapper +sql自定义查询
一: 需要自定义的QueryWrapper查询工具类,定义查询规则
public static final String SQL_RULES_COLUMN = "SQL_RULES_COLUMN"; private static final String BEGIN = "_begin"; // 字段范围查询开始标识 private static final String END = "_end"; // 字段范围查询结束标识 private static final String STAR = "*"; // 字段模糊查询标识 private static final String COMMA = ","; private static final String NOT_EQUAL = "!";
二: 正常的QueryWrapper查询,在mapper文件中使用 @Param(Constants.WRAPPER)
List<Emdj> listAll(IPage<Emdj> page, @Param(Constants.WRAPPER) QueryWrapper<Emdj> queryWrapper);
xml文件中使用ew.customSqlSegment,<where>标签可以不加
<select id="listAll" resultType="net.zazn.modules.discipline.entity.Emdj"> select id,lffh,xm,jsh,szrq,emlx,spzt,gjmj,flag,jlzt from emdj <where>${ew.customSqlSegment}</where> </select>
总结
到此这篇关于mybatis-plus自带QueryWrapper自定义sql实现复杂查询的文章就介绍到这了,更多相关mybatis-plus自定义sql实现复杂查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!