MyBatis-Plus+mysql5.7动态拼接sql语句分页查询⾃定义sql查询条件分
组排序
jquery设置cookie在使⽤srpingboot2.x+mybatis-plus框架是遇到特殊需求时研究mybatis-plus的条件构造器动态拼接sql查询,这个查询接⼝涉及到了⾃定义sql,动态拼接sql,分页,求和,分组,排序。
可以直接看业务实现⽅法
⾸先说⼀下接⼝的需求:
⼊参JSON:
web缓存技术1 {
2 "from": "2020-5-29",
3 "limit": 10,
4 "offset": 0,
5 "order": "hitCount",
openstack的定位是什么6 "page": 1,
7 "search": "",
8 "sort": "desc",
9 "sortDirection": "",
10 "to": "2020-6-10"
11 }
⼊参注释说明:
{
"from": "开始查询时间",
"limit": 条数,
"offset": 0,
"order": "需要排序的字段",
"page": 页码,
"search": "查询条件",
"sort": "排序规则",
"sortDirection": "",
"to": "结束查询时间"
}
然后先写接⼝实现:
1 @PostMapping("categoryList")
2public R getCategoryList(@Validated @RequestBody QaDetailSearchVo vo){
3 RobotPage pageHelper = new Page(),vo.getLimit());
4return R.ok(iStatQaService.findQaStatCategory(pageHelper, vo));
5 }
解释:POST请求,R 是⾃定义的返回类型,RobotPage是为了实现⼀些特殊返回值继承于mybatsi-plus分页的Ipage:
1public class RobotPage<T> extends Page<T> implements Serializable {}
重点是业务实现类和mapper层:
对于⼀般的查询mybatis-plus的条件构造器已经可以满⾜了,例如:
1 SysUser sysUser = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
2 .select(SysUser::getUserId, SysUser::getUsername, SysUser::getPhone, SysUser::getEmail, SysUser::getPassword, SysUser::getDeptId, SysUser::getJobId, SysUser::getAvatar)
3 .eq(SysUser::getUsername, username));
但是对于⼀些需要复杂的或者多表的操作就需要⾃定义sql语句了,⽰例:
⾸先是mapper⾃定义分页查询接⼝:
1 @Select("SELECT s.category_id as id, s.category_name as category, SUM(s.hit_count) as hitCount, SUM(s.solve_count) as resolvedCount, _solve_count) as unresolvedCount " +
2 "FROM core_stat_qa as s ${ew.customSqlSegment}")
3 IPage<QaDetailCategoryListVo> findCategoryListByParams(IPage<QaDetailCategoryListVo> page, @Param(Constants.WRAPPER) QueryWrapper<StatQa> wrappers);
这部分官⽹给的有⽰例:
业务接⼝不⽤看直接是实现类:
1 @Override
2public Grid findQaStatCategory(Page<QaDetailCategoryListVo> page, QaDetailSearchVo vo) {
3//声明返回
4 Grid grid = new Grid();adonet教程
5//组装查询语句
6 QueryWrapper<StatQa> qaQueryWrapper = new QueryWrapper<>();
7//模糊查询
8 qaQueryWrapper.like(StringUtils.Search()),"category_name",vo.getSearch());mysql语句顺序>企业免费建站
9//where条件
10 ("create_time", DateUtil.From(),"yyyy-MM-dd"));
11 qaQueryWrapper.lt("create_time",DateUtil.To(), "yyyy-MM-dd"));
12//分组
13 upBy("category_id","category_name");
14//排序
15 derBy(true, !"desc".Sort()),vo.getOrder());
16//调⽤⾃定义sql语句
17 IPage<QaDetailCategoryListVo> statQaIPage = baseMapper.findCategoryListByParams(page, qaQueryWrapper);
18//抽取list
19 List<QaDetailCategoryListVo> statQaList = Records();
20 grid.setList(statQaList);
21 grid.Total());
22return grid;
23 }
需要解释的:
排序orderBy⽅法中的第⼀个true官⽹上也是给出解释的:表⽰该条件是否加⼊最后⽣成的sql中。!"desc".Sort()) 是排序规则 asc和desc
调⽤mapper⾃定义sql就是:
baseMapper.findCategoryListByParams(page, qaQueryWrapper);
接⼝完成。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论