工具类系列---【tk-mybatis查询条件组装类】

tk-mybatis的使用教程

1.引入依赖

            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>2.1.5</version>
            </dependency>

2.mapper接口继承基础增删改查Mapper,批量增删改查MySqlMapper

public interface StudentMapper extends Mapper<Student>, MySqlMapper<Student> {
}

3.在启动类上加上@MapperScan("com.study.test.mapper.**"),注意导入tkMybatis的包下的注解。

注意:

   1.必须要在实体类上加上@Id注解,不然tk-mybatis找不到主键,导致修改和删除时where后面跟上所有属性(例update sys_menu set id ="234242",name = "张三",age=19 where id=? and name =? and age =?),进而导致修改失败。

   2.可以在实体类名上加上@Table(name="sys_menu")注解,在字段名上加上@Colum(name = "del_flag")注解。这些注解都是javax包下的。

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<T> {
    
    public static <T> Example build(T param){
        Example example = new Example(param.getClass());
        example.setOrderByClause("create_time desc");
        return example;
    }

  //把param中值为空串的字段设置成null,这样tk-mybatis就不会拼接这个条件了
public static <T> Example 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; } }
复制代码

5.多条件查询示例

复制代码
Student student = BeanUtil.copyProperties(param,Student.class);
PageHelper.startpage(param.getPageSize(),param.getPageNo());
#这里注意,多个条件用同一个exmple.createCriteria()去连接,不能直接用example Example example
= ExampleUtil.andEqualTo(param); List<Student> voList = studentMapper.selectByExample(example); return new PageInfo<>(voList);



#时间范围查询,这里以日期为例,前端传来的"yyyy-MM-dd"日期字符串
String beginDateStr = param.getBeginDate();
String endDateStr = param.getEndDate();
if(StrUtil.isNotBlank(beginDateStr) &&StrUtil.isNotBlank(endDateStr)){
  #这里的日期格式要和字符串的日期格式严格一致,日期用LocalDate接收,日期时间用LocalDateTime接收,
#例:endDateStr = "2022-06-22",对应"yyyy-MM-dd",如果格式不一致会报错
  DateTimeFormatter dtf =DateTimeFormatter.ofPattern("yyyy-MM-dd");
  LocalDate beginDate =LocalDate.parse(beginDateStr,dtf);
  LocalDate endDate = LocalDate.parse(endDateStr,dtf);
  criteria.andBetween("createTime",beginDate.atStartOfDay(),endDate.plusDays(1).atStartOfDay())
}
 
复制代码

posted on   少年攻城狮  阅读(448)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-03-09 开发中遇到的问题---【 is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-pr oxying】
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示