工具类系列---【tk-mybatis查询条件组装类】
tk-mybatis的使用步骤:
1.引入依赖
<dependency> <groupId>tk.mybatisgroupId> <artifactId>mapper-spring-boot-starterartifactId> <version>2.1.5version> dependency>
2.mapper接口继承基础增删改查Mapper,批量增删改查MySqlMapper
public interface StudentMapper extends Mapper<Student>, MySqlMapper<Student> { }
3.在启动类上加上@MapperScan("com.study.test.mapper.**"),注意导入tkMybatis的包下的注解。
4.查询条件工具类
package com.fast.common.util; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import lombok.extern.slf4j.Slf4j; import tk.mybatis.mapper.entity.Example; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * tk-mybatis条件组装工具类 * * @author hujw * @since 2022/3/9 */ @Slf4j public class ExampleUtil{ public static Example build(T param){ Example example = new Example(param.getClass()); example.setOrderByClause("create_time desc"); return example; }
//把param中值为空串的字段设置成null,这样tk-mybatis就不会拼接这个条件了 public staticExample andEqualTo(T param){ Example example = build(param); Example.Criteria criteria = example.createCriteria(); Class<?> target = param.getClass(); Field[] fields = target.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String fieldName = field.getName(); if (field.getType().equals(String.class)){ String firstLatter = fieldName.substring(0, 1); String upperFieldName = fieldName.replaceFirst(firstLatter, firstLatter.toUpperCase()); try { Method getMethod = target.getMethod("get" + upperFieldName); String str = (String) getMethod.invoke(param); if (str !=null && StringUtils.isNotBlank(str.trim())){ field.set(param,null); } } catch (Exception e) { log.warn("ExampleUtil.addEqualTo execute fail,cause:{}",e); } } } criteria.andEqualTo(param); return example; } }
4.多条件查询示例
Student student = BeanUtil.copyProperties(param,Student.class); PageHelper.startpage(param.getPageSize(),param.getPageNo()); Example example = ExampleUtil.andEqualTo(param); ListvoList = studentMapper.selectByExample(example); return new PageInfo<>(voList);