mybatis-plus 指定列指定值排序

问题:由于使用mybatis-plus的查询功能,是通过封装querywrapper实现的,SQL可控性不高,有部分逻辑不好控制,例如排序。

方案:使用last方法补充尾部逻辑(https://baomidou.com/guide/wrapper.html#last

样例1:

通过更新时间和创建时间倒序排序

QueryWrapper<Employee> queryWrapper = QueryGenerator.initQueryWrapper(employee, req.getParameterMap());
queryWrapper.eq("ORG_ID",sysUser.getOrgCode());
queryWrapper.last("order by nvl2(update_time, update_time, create_time) desc");

样例2:

通过字段状态和创建时间排序(状态为在职的员工置顶,且按更新时间升序排序)

QueryWrapper<Employee> queryWrapper = QueryGenerator.initQueryWrapper(employee, req.getParameterMap());
queryWrapper.last("order by case when staff_status = '1' then 1 else 2 end, update_date asc"); // staff_status 1是在职 2是离职

 

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus 中,你可以使用 PageHelper 插件来实现分页排序和将 null 排在最后的功能。 首先,确保你已经正确地配置了 MyBatis-Plus 和 PageHelper 插件。 然后,在你的查询方法中,使用 PageHelper.startPage 方法来启动分页功能,并使用 PageHelper.orderBy 方法来指定排序字段和排序方式。例如: ```java import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public IPage<User> getUsersWithPaginationAndSort() { // 使用 PageHelper.startPage 方法开启分页功能 Page<User> page = PageHelper.startPage(1, 10); // 使用 PageHelper.orderBy 方法指定排序字段和排序方式 PageHelper.orderBy("name ASC NULLS LAST"); // 执行查询 List<User> userList = userMapper.selectList(null); // 将查询结果封装到 Page 对象中 return page.setRecords(userList); } } ``` 上述代码示例中,我们使用了 `name ASC NULLS LAST` 来指定按照 name 字段升序排序,并且将 null 排在最后。 请根据你的实际需求调整排序字段和排序方式。注意,在不同的数据库中,对于 null 的处理方式可能会有所不同,可以根据实际情况来调整排序语句。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值