目录
常用写法
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打印
补充:or查询
LambdaQueryWrapper<Entity> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.select(Entity::getCode);
queryWrapper.eq(Entity::getAge, 10);
queryWrapper.and(w -> w.eq(Entity::getName, "张三").or().eq(Entity::getName2, "张三"));
List<Entity> list = service.list(queryWrapper);
打印sql如下
SELECT code FROM table WHERE (age = ? AND (name = ? OR name2 = ? ))
==> Parameters: 10(Integer), 张三(String), 张三(String)