一些挺不错的工具类
1.自己整合的querywrapper工具类
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Administrator
*/
public class QueryWrapperUtils {
private static Pattern linePattern = Pattern.compile("_(\\w)");
/** 下划线转驼峰 */
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** 驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)}) */
public static String humpToLine(String str) {
return str.replaceAll("[A-Z]", "_$0").toLowerCase();
}
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/** 驼峰转下划线,效率比上面高 */
public static String humpToLine2(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String lineToHump = lineToHump("f_parent_no_leader");
System.out.println(lineToHump);
// fParentNoLeader
System.out.println(humpToLine(lineToHump));
// f_parent_no_leader
System.out.println(humpToLine2(lineToHump));
// f_parent_no_leader
}
/**
*
* @Description
* 1.clazz类型参数返回该类型的QueryWrapper,条件为dto参数中的属性,null值不构建条件.
* 2.其中String类型默认是用模糊查询,需要精准匹配请在属性后面加上大写的“EQ”,特定的order属性作为排序的字段名.
* 3.其中Boolean类型为排序判断,true倒序,false升序,并且order为空的时候不做排序,并且需要提供getFlag方法.
* 4.其中时间类型是LocalDateTime,如果需要区间,会判断属性是否以大写的“START”或者“END”结尾进行大于开始时间,小于结束时间查询.
* 5.其中布尔类型或者其他基本类型都需要使用包装类
* @Author DengYiFan
* @Param [clazz 任意类, dto 条件参数实体类]
* @Return com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<T>
*
*/
public static <T> QueryWrapper<T> getQueryWrapper(Class<T> clazz,Object dto) {
QueryWrapper<T> wrapper = new QueryWrapper<>();
Field[] field = dto.getClass().getDeclaredFields();
boolean flag = true;
String order = null;
for (int j = 0; j < field.length; j++) {
try {
String fieldName = field[j].getName();
String name = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
String type = field[j].getGenericType().toString();
Method m = dto.getClass().getMethod("get" + name);
Object value = m.invoke(dto);
if (value != null) {
switch (type) {
case "class java.lang.String":
if (StringUtils.isBlank((String)value)){
break;
}
if ("order".equals(fieldName)){
order = (String) value;
break;
}
if (fieldName.endsWith("EQ")){
wrapper.eq(humpToLine2(fieldName.substring(0,fieldName.length()-2)),(String) value);
break;
}
wrapper.like(humpToLine2(fieldName), (String) value);
break;
case "class java.lang.Integer":
wrapper.eq(humpToLine2(fieldName), (Integer) value);
break;
case "class java.lang.Short":
wrapper.eq(humpToLine2(fieldName), (Short) value);
break;
case "class java.lang.Double":
wrapper.eq(humpToLine2(fieldName), (Double) value);
break;
case "class java.lang.Boolean":
flag = (boolean) value;
break;
case "class java.time.LocalDateTime":
if (fieldName.endsWith("START")){
wrapper.gt(humpToLine2(fieldName.substring(0,fieldName.length()-5)),(LocalDateTime) value);
break;
}
if (fieldName.endsWith("END")){
wrapper.lt(humpToLine2(fieldName.substring(0,fieldName.length()-3)),(LocalDateTime) value);
break;
}
wrapper.eq(humpToLine2(fieldName), (LocalDateTime) value);
break;
default:break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (order != null){
if (flag){
wrapper.orderByDesc(QueryWrapperUtils.humpToLine2(order));
}else {
wrapper.orderByAsc(QueryWrapperUtils.humpToLine2(order));
}
}
return wrapper;
}
/**
*
* @Date: 2021/7/27 13:43
* @Description: 此方法同上,不做泛型限制
*/
public static QueryWrapper getGeneralQuery(Object dto) {
QueryWrapper wrapper = new QueryWrapper<>();
Field[] field = dto.getClass().getDeclaredFields();
boolean flag = true;
String order = null;
for (int j = 0; j < field.length; j++) {
try {
String fieldName = field[j].getName();
String name = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
String type = field[j].getGenericType().toString();
Method m = dto.getClass().getMethod("get" + name);
Object value = m.invoke(dto);
if (value != null) {
switch (type) {
case "class java.lang.String":
if (StringUtils.isBlank((String)value)){
break;
}
if ("order".equals(fieldName)){
order = (String) value;
break;
}
if (fieldName.endsWith("EQ")){
wrapper.eq(humpToLine2(fieldName.substring(0,fieldName.length()-2)),(String) value);
break;
}
wrapper.like(humpToLine2(fieldName), (String) value);
break;
case "class java.lang.Integer":
wrapper.eq(humpToLine2(fieldName), (Integer) value);
break;
case "class java.lang.Short":
wrapper.eq(humpToLine2(fieldName), (Short) value);
break;
case "class java.lang.Double":
wrapper.eq(humpToLine2(fieldName), (Double) value);
break;
case "class java.lang.Boolean":
flag = (boolean) value;
break;
case "class java.time.LocalDateTime":
if (fieldName.endsWith("START")){
wrapper.gt(humpToLine2(fieldName.substring(0,fieldName.length()-5)),(LocalDateTime) value);
break;
}
if (fieldName.endsWith("END")){
wrapper.lt(humpToLine2(fieldName.substring(0,fieldName.length()-3)),(LocalDateTime) value);
break;
}
wrapper.eq(humpToLine2(fieldName), (LocalDateTime) value);
break;
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (order != null){
if (flag){
wrapper.orderByDesc(QueryWrapperUtils.humpToLine2(order));
}else {
wrapper.orderByAsc(QueryWrapperUtils.humpToLine2(order));
}
}
return wrapper;
}
}
2.String工具类
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
* @author ThinkGem
* @version 2013-05-22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
public static String lowerFirst(String str){
if(StringUtils.isBlank(str)) {
return "";
} else {
return str.substring(0,1).toLowerCase() + str.substring(1);
}
}
public static String upperFirst(String str){
if(StringUtils.isBlank(str)) {
return "";
} else {
return str.substring(0,1).toUpperCase() + str.substring(1);
}
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)){
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 缩略字符串(不区分中英文字符)
* @param str 目标字符串
* @param length 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
/**
* 缩略字符串(替换html)
* @param str 目标字符串
* @param length 截取长度
* @return
*/
public static String rabbr(String str, int length) {
return abbr(replaceHtml(str), length);
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val){
if (val == null){
return 0D;
}
try {
return Double.valueOf(trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(Object val){
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val){
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val){
return toLong(val).intValue();
}
}
3.代码生成器(需要引入pom依赖,已经放在注解里了)
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneratorDemo {
@Test
public void testGenerator() {
//1. 全局配置
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) // 是否支持AR模式
.setAuthor("作者") // 作者
.setOutputDir("D:/java/code") // 生成路径
.setFileOverride(true) // 文件覆盖
.setIdType(IdType.ASSIGN_ID) // 主键策略
.setEnableCache(false) //是否开启二级缓存
.setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I
// IEmployeeService
.setBaseResultMap(true)
.setBaseColumnList(true);
//2. 数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
.setDriverName("com.mysql.cj.jdbc.Driver")
.setUrl("jdbc:mysql:")
.setUsername("root")
.setPassword("123");
//3. 策略配置
StrategyConfig stConfig = new StrategyConfig();
List<TableFill> tableFillList = new ArrayList<>();
tableFillList.add(new TableFill("createTime", FieldFill.INSERT));
tableFillList.add(new TableFill("updateTime", FieldFill.UPDATE));
stConfig.setCapitalMode(true) //全局大写命名
// .setDbColumnUnderline(true) // 指定表名 字段名是否使用下划线
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
/*.setTablePrefix("tab_")
.setInclude("tab_user")*/ // 生成的表
.setEntityLombokModel(true)
.setVersionFieldName("version")
.setLogicDeleteFieldName("isDelete")
.setTableFillList(tableFillList);
// .setSuperEntityClass("BaseEntity")
// .setSuperEntityColumns("appId", "version", "isDelete", "createTime", "createBy", "updateTime", "updateBy");
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.aa.bb")
.setMapper("mapper")
.setService("service")
.setController("web")
.setEntity("entity")
.setXml("mapper");
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
//6. 执行
ag.execute();
/**
/**
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
*/
*/
}
}