mybatis plus 条件构造器 多字段模糊搜索
使用理由: 每次去写很麻烦, 写成一个公共方法 一次痛苦, 多次受益, 封装思想
使用简单方便
/*** 数组缩容** @param conditions* @return*/public static String[] removeFirstElement(String... conditions) {return Arrays.copyOfRange(conditions, 1, conditions.length);}
import com.aisce.common.utils.Maths.MathUtils;
import com.aisce.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;/*** 构造器 构造方法封装** @Author pzy* @Description: TODO* @Version 0.1.0*/
public class WrappersConstructor {/*** 条件构造器之 模糊搜索公共字段 弱校验** @param queryWrapper* @param searchName* @param conditions* @param * @return*/public static QueryWrapper wrapperConstructor(QueryWrapper queryWrapper, String searchName, String... conditions) {if (conditions == null || conditions.length < 1) {return new QueryWrapper<>();}return WrappersConstructor.wrapperBaseConstructor(queryWrapper, searchName, conditions);}/*** 条件构造器之 模糊搜索公共字段 强校验* Force Re-Check** @param forceCheck (传递true 校验, 然后抛异常, 不可以不传递)* @param queryWrapper* @param searchName* @param conditions* @param * @return*/public static QueryWrapper wrapperConstructor(boolean forceCheck, QueryWrapper queryWrapper, String searchName, String... conditions) {//用法两个if (conditions == null || conditions.length < 1) {if (forceCheck) {throw new RuntimeException("Error ways at wrapperConstructor[args1,args2,args3...], args3 value of empty is not allowed");}return new QueryWrapper<>();}return WrappersConstructor.wrapperBaseConstructor(queryWrapper, searchName, conditions);}/*** 条件构造器 模糊搜索基础数据创建** @param queryWrapper* @param searchName* @param conditions* @param * @return*/private static QueryWrapper wrapperBaseConstructor(QueryWrapper queryWrapper, String searchName, String... conditions) {return queryWrapper.and(StringUtils.isNotBlank(searchName), wrapper -> {wrapper.like(conditions[0], searchName);//计算数组String[] newConditions = MathUtils.removeFirstElement(conditions);if (newConditions.length > 0) {//拼接 第一个没有or 后面有orfor (String condition : newConditions) {wrapper.or().like(condition, searchName);}}});}}
queryWrapper = WrappersConstructor.wrapperConstructor(queryWrapper, searchName, "username", "telephone");
-> ps: 都不填, 不可以在最后面使用
queryWrapper = WrappersConstructor.wrapperConstructor(true,queryWrapper, searchName);
(自由修改, 代码在上面)
Error ways at wrapperConstructor[args1,args2,args3...], args3 value of empty is not allowed
封装思想,实现的过程, 持续更新吧~~~