当前位置: 首页 > news >正文

拼接sql字符串工具类

  1. 申明注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StrSqlAnnotation {/*** 表字段名称,如"create_name"** @return*/String filedName() default "";/*** 类型 STR-字符串 LIST-集合* {@link com.ltd.ccci.svc.transport.api.constant.CommonSymbolConstant}** @return*/String type() default CommonSqlKeyWordConstant.LIKE_IN_TYPE;}
  1. 相关常量类
    a. sql拼接常量:CommonSqlKeyWordConstant
public class CommonSqlKeyWordConstant {public static final String AND = "AND ";public static final String OR = "OR";public static final String NOT = "NOT";public static final String IN = "IN";public static final String NOT_IN = "NOT IN";public static final String LIKE = "LIKE";public static final String NOT_LIKE = "NOT LIKE";public static final String EQ = "=";public static final String NE = "<>";public static final String GT = ">";public static final String GE = ">=";public static final String LT = "<";public static final String LE = "<=";/*** 搜索条件-like or eq*/public static final String LIKE_IN_TYPE = "LIKE_IN_TYPE";}

b. 符号常量:CommonSymbolConstant(可不使用)

public class CommonSymbolConstant {private CommonSymbolConstant() {}/*** 横杠*/public static final String BAR = "-";/*** 波浪号*/public static final String TILDE = "~";/*** 下划线*/public static final String UNDERLINE = "_";/*** 斜杠*/public static final String SLASH = "/";/*** 冒号*/public static final String COLON = ":";/*** 分号*/public static final String SEMICOLON = ";";/*** 逗号*/public static final String COMMA = ",";/*** 点*/public static final String POINT = ".";/*** 顿号*/public static final String PAUSE = "、";/*** 点*/public static final String EMPTY = "";/*** 空格*/public static final String BLANK = " ";/*** 单引号*/public static final String SINGLE_QUOTES = "'";/*** 正括号*/public static final String OPEN_BRACKET = "(";/*** 反括号*/public static final String CLOSE_BRACKET = ")";
}
  1. 工具类:SearchUtil
public class SearchUtil {/*** 翻译单个实体** @param obj 实体信息*/public static <T, V> QueryWrapper<V> getSearchWrapper(T obj, Class<V> ignoredClazz) {QueryWrapper<V> wrapper = new QueryWrapper<>();// 防止未传条件不拼接where条件if (!ObjectUtil.isEmpty(obj)) {try {Class<?> aClass = obj.getClass();Map<String, Field> fields = getAllFileds(aClass);for (Field field : fields.values()) {if (field.isAnnotationPresent(StrSqlAnnotation.class)) {field.setAccessible(true);StrSqlAnnotation annotation = field.getAnnotation(StrSqlAnnotation.class);String filedName = annotation.filedName();if (StringUtils.isBlank(filedName)) {filedName = StrUtil.toUnderlineCase(field.getName());}String type = annotation.type();Object object = field.get(obj);if (ObjectUtil.isNotEmpty(object)) {Class<?> filedClass = object.getClass();String str = object.toString().trim();// 日期格式单独转化if (filedClass.equals(LocalDateTime.class)) {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);str = ((LocalDateTime) object).format(dateTimeFormatter);} else if (filedClass.equals(LocalDate.class)) {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);str = ((LocalDate) object).format(dateTimeFormatter);}switch (type) {// like incase CommonSqlKeyWordConstant.LIKE_IN_TYPE -> {String[] split = str.split(",");if (split.length > 1) {wrapper.in(filedName, Arrays.asList(split));} else {wrapper.like(filedName, str);}}// incase CommonSqlKeyWordConstant.IN -> {String parse = JSONUtil.toJsonStr(object);List<String> list = JSONUtil.toList(parse, String.class);// LocalDateTime类型如果是集合传入,接收时类型为Long。时间集合建议传List<String>if (CollUtil.isNotEmpty(list)) {wrapper.in(filedName, list);}}// likecase CommonSqlKeyWordConstant.LIKE -> wrapper.like(filedName, str);// =case CommonSqlKeyWordConstant.EQ -> wrapper.eq(filedName, str);// >=case CommonSqlKeyWordConstant.GE -> wrapper.ge(filedName, str);// <=case CommonSqlKeyWordConstant.LE -> wrapper.le(filedName, str);default -> {}}}}}} catch (Exception e) {throw new ApiException(MsgUtils.getMessage("biz.common.StrFiledError"));}}return wrapper;}/*** 获取所有字段含父级** @param aClass 实体类* @return 所有字段信息*/private static Map<String, Field> getAllFileds(Class<?> aClass) {// key-字段名  value-字段信息Map<String, Field> fileds = new HashMap<>();List<Field> fieldList = new ArrayList<>();Class<?> tempClass = aClass;//当父类为null的时候说明到达了最上层的父类(Object类).while (tempClass != null) {fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));//得到父类,然后赋给自己tempClass = tempClass.getSuperclass();}for (Field field : fieldList) {fileds.put(field.getName(), field);}return fileds;}}
  1. 使用示例
    实体类注解使用
    @Schema(title = "线路编号")@StrSqlAnnotation(filedName = "no")private String no;@Schema(title = "物流供应商编码-单个查询-精确查询")@StrSqlAnnotation(type = CommonSqlKeyWordConstant.EQ)private String logisticsSupplierCode;@Schema(title = "物流合同号")@StrSqlAnnotation()private String logisticsContractNo;@Schema(title = "物流供应商编码")@StrSqlAnnotation(filedName = "logistics_supplier_code", type = CommonSqlKeyWordConstant.IN)private List<String> logisticsSupplierCodes;

LambdaQueryWrapper使用示例

private LambdaQueryWrapper<LineMainDO> dealSearchInfo(LinePageReq req, SFunction<LineMainDO, ?> sortFiled, boolean whetherAsc) {LambdaQueryWrapper<LineMainDO> lambdaQuery = SearchUtil.getSearchWrapper(req, LineMainDO.class).lambda();if (CollUtil.isEmpty(req.getSortItems())) {lambdaQuery.orderBy(true, whetherAsc, sortFiled);}return lambdaQuery;}

xml使用示例
service

    public CommonPage<ReceiptPageDTO> queryPage(ReceiptPageReq req) {QueryWrapper<ReceiptMainDO> searchWrapper = SearchUtil.getSearchWrapper(req, ReceiptMainDO.class);IPage<ReceiptPageDTO> page = receiptMainMapper.queryPage(MPPager.buildPage(req), searchWrapper);return MPCommonPage.restPage(page );}

mapper

  /*** 运输签收分页(明细联表)** @param ipage 分页信息* @param sql   高级搜索条件sql* @return 分页信息*/IPage<ReceiptPageDTO> queryPage(Page<ReceiptMainDO> ipage, @Param(Constants.WRAPPER) QueryWrapper<ReceiptMainDO> sql);

xml

 <select id="queryPage" resultType="com.ltd.ccci.svc.transport.api.dto.receipt.ReceiptPageDTO"><select id="queryPage" resultType="com.ltd.ccci.svc.transport.api.dto.receipt.ReceiptPageDTO">SELECT *FROM receipt_main m,receipt_detail d<choose><when test="ew.customSqlSegment != null and ew.customSqlSegment != ''">${ew.customSqlSegment} and</when><otherwise>where</otherwise></choose>m.id = d.receipt_main_idand d.del_flag = 0and m.del_flag = 0order by m.update_time, d.create_time, d.id</select>

相关文章:

  • AB测试实战
  • Qt5学习笔记
  • HCL模拟器下做M-LAG测试(以及和华为配置对比)-二层架构
  • k8s更改master节点IP
  • Pycharm创建Conda虚拟环境时显示CondaHTTPErOT
  • SpringBoot高手之路-springboot原理篇
  • 【深度学习基础】模型文件介绍
  • Tomcat 配置:一文掌握所有要点
  • 【学习笔记】Redis-AOF日志重写的机制
  • 【AI论文与新生技术】Follow-Your-Emoji:精细可控且富有表现力的自由式人像动画技术
  • 【深度学习】目标检测,Faster-RCNN算法训练,使用mmdetection训练
  • Spring boot项目
  • 商城项目【尚品汇】07分布式锁-2 Redisson篇
  • npm发布自己的插件包
  • Ansys的电磁场分析和系统电路仿真软件Electronics 2024 R1版本在Windows系统的下载与安装配置
  • $translatePartialLoader加载失败及解决方式
  • GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上)...
  • input实现文字超出省略号功能
  • iOS 颜色设置看我就够了
  • Java教程_软件开发基础
  • Python进阶细节
  • Selenium实战教程系列(二)---元素定位
  • SpingCloudBus整合RabbitMQ
  • sublime配置文件
  • ⭐ Unity + OpenCV 实现实时图像识别与叠加效果
  • Zepto.js源码学习之二
  • 程序员最讨厌的9句话,你可有补充?
  • 仿天猫超市收藏抛物线动画工具库
  • 关于Android中设置闹钟的相对比较完善的解决方案
  • 聚类分析——Kmeans
  • 爬虫进阶 -- 神级程序员:让你的爬虫就像人类的用户行为!
  • 如何使用 JavaScript 解析 URL
  • 使用iElevator.js模拟segmentfault的文章标题导航
  • 微信如何实现自动跳转到用其他浏览器打开指定页面下载APP
  • 自制字幕遮挡器
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • !$boo在php中什么意思,php前戏
  • #Datawhale AI夏令营第4期#AIGC文生图方向复盘
  • #Js篇:单线程模式同步任务异步任务任务队列事件循环setTimeout() setInterval()
  • (C++17) optional的使用
  • (Mac上)使用Python进行matplotlib 画图时,中文显示不出来
  • (pojstep1.1.1)poj 1298(直叙式模拟)
  • (二)springcloud实战之config配置中心
  • (附源码)springboot工单管理系统 毕业设计 964158
  • (含答案)C++笔试题你可以答对多少?
  • (几何:六边形面积)编写程序,提示用户输入六边形的边长,然后显示它的面积。
  • (简单有案例)前端实现主题切换、动态换肤的两种简单方式
  • (十三)Maven插件解析运行机制
  • (转)Android学习系列(31)--App自动化之使用Ant编译项目多渠道打包
  • ***通过什么方式***网吧
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .NET 服务 ServiceController
  • .NET 使用配置文件
  • .net快速开发框架源码分享
  • 。Net下Windows服务程序开发疑惑