本文以 SystemUserMapper 和 SystemUserService 为实战案例,系统讲解 MyBatis-Plus 高级查询的三种核心技巧:
注解式 SQL:通过 @Select 注解配合 ${ew.customSqlSegment} 占位符,无需 XML 即可实现动态条件拼接
Lambda 条件构造器:使用 LambdaQueryWrapper 替代字符串字段名,利用 like、eq 等方法构建类型安全的条件,配合 Hutool 的 StrUtil 实现动态条件过滤
JSON 字段查询:通过 wrapper.apply() 方法拼接 JSON_EXTRACT 函数,实现 JSON 字段值的精准匹配,多个 apply 自动用 AND 连接
泛型分页:IPage<Entity> 作为参数和返回值,与 MyBatis-Plus 分页插件无缝集成
通过本文,你将掌握如何在不编写 XML 的前提下,优雅地实现包含模糊查询、非空判断、JSON 字段提取等复杂场景的动态分页查询。
javaimport cn.odboy.system.dal.dataobject.SystemUserTb;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface SystemUserMapper {
@Select("SELECT * FROM system_user ${ew.customSqlSegment}")
IPage<SystemUserTb> searchUser(IPage<SystemUserTb> page, @Param(Constants.WRAPPER) Wrapper<SystemUserTb> wrapper);
}
javaimport cn.hutool.core.util.StrUtil;
import cn.odboy.system.dal.dataobject.SystemUserTb;
import cn.odboy.system.dal.mysql.SystemUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SystemUserService {
@Autowired
private SystemUserMapper systemUserMapper;
public void searchUser(IPage<SystemUserTb> page, SystemUserTb args) {
LambdaQueryWrapper<SystemUserTb> wrapper = new LambdaQueryWrapper<>();
if (args != null) {
wrapper.like(StrUtil.isNotEmpty(args.getNickName()), SystemUserTb::getNickName, args.getNickName());
wrapper.like(StrUtil.isNotEmpty(args.getUsername()), SystemUserTb::getUsername, args.getUsername());
// 多个apply会自动拼接 AND 关键字
wrapper.apply(args.getDeptId() != null, "JSON_EXTRACT(dept_id, '$.value') = {0}", args.getDeptId());
}
return systemUserMapper.searchUser(page, wrapper);
}
}


本文作者:Odboy
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC 4.0 BY-SA 许可协议。转载请注明出处!