package com.yuanchu.mom.utils; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.AllArgsConstructor; import lombok.CustomLog; import org.springframework.stereotype.Component; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; /* * 李林 * 生成SQL语句*/ @Component @AllArgsConstructor public class QueryWrappers { public static QueryWrapper queryWrappers(T entity) { if (ObjectUtil.isEmpty(entity)) return null; Class aClass = entity.getClass(); QueryWrapper wrapper = Wrappers.query(); List fieldList = new ArrayList<>(); while (aClass != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(aClass.getDeclaredFields()))); aClass = aClass.getSuperclass(); } for (Field field : fieldList) { field.setAccessible(true); Object value; try { value = field.get(entity); } catch (IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException("查询条件生成错误"); } // System.out.println(field.getName() + "|" + (value == null || value.equals("")) + "|" + value); if(value == null || value.equals("")){ continue; } if (!field.getName().equals("orderBy")) { if(value.getClass()== LocalDateTime.class){ wrapper.like(StrUtil.toUnderlineCase(field.getName()), ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); }else{ wrapper.like(StrUtil.toUnderlineCase(field.getName()), value); } } else { Map map = (Map) value; if(map.get("order")!=null){ wrapper.orderBy(true, map.get("order").equals("asc"), StrUtil.toUnderlineCase(map.get("field"))); } } } System.out.println(wrapper.getExpression().getSqlSegment()); return wrapper; } }