diff --git a/lib/jpaHelper-release.jar b/lib/jpaHelper-release.jar deleted file mode 100644 index 7e04284..0000000 Binary files a/lib/jpaHelper-release.jar and /dev/null differ diff --git a/lib/jpaHelper/.gitignore b/lib/jpaHelper/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/lib/jpaHelper/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/lib/jpaHelper/pom.xml b/lib/jpaHelper/pom.xml new file mode 100644 index 0000000..587f689 --- /dev/null +++ b/lib/jpaHelper/pom.xml @@ -0,0 +1,56 @@ + + 4.0.0 + jpaHelper + jar + release + + + org.springframework.boot + spring-boot-starter-parent + 3.3.3 + + + + + 21 + + + + + cn.hutool + hutool-all + 5.8.25 + + + com.mysql + mysql-connector-j + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + io.swagger.core.v3 + swagger-annotations-jakarta + 2.2.19 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + \ No newline at end of file diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/CreateTime.java b/lib/jpaHelper/src/main/java/com/cym/bean/CreateTime.java new file mode 100644 index 0000000..6b71c20 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/CreateTime.java @@ -0,0 +1,12 @@ +package com.cym.bean; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface CreateTime { + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/InitValue.java b/lib/jpaHelper/src/main/java/com/cym/bean/InitValue.java new file mode 100644 index 0000000..0060545 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/InitValue.java @@ -0,0 +1,14 @@ +package com.cym.bean; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface InitValue { + + String value(); + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/OrderBy.java b/lib/jpaHelper/src/main/java/com/cym/bean/OrderBy.java new file mode 100644 index 0000000..8ae5d55 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/OrderBy.java @@ -0,0 +1,48 @@ +package com.cym.bean; + +public class OrderBy { + Direction direction; + String column; + String orderByStr; + + + + public static enum Direction { + ASC, DESC; + } + + public OrderBy(Direction direction, String column) { + this.direction = direction; + this.column = column; + } + + public OrderBy() { + + } + + + public String getOrderByStr() { + return orderByStr; + } + + public void setOrderByStr(String orderByStr) { + this.orderByStr = orderByStr; + } + + public Direction getDirection() { + return direction; + } + + public void setDirection(Direction direction) { + this.direction = direction; + } + + public String getColumn() { + return column; + } + + public void setColumn(String column) { + this.column = column; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/Page.java b/lib/jpaHelper/src/main/java/com/cym/bean/Page.java new file mode 100644 index 0000000..19c873b --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/Page.java @@ -0,0 +1,99 @@ +package com.cym.bean; + +import java.util.ArrayList; +import java.util.List; + +import io.swagger.v3.oas.annotations.media.Schema; + +@Schema(description = " 分页返回类") +public class Page { + @Schema(description = "总记录数") + Long total = 0l; + @Schema(description = "起始页,从1开始") + Integer pageNum = 1; + @Schema(description = "每页记录数,默认为10") + Integer pageSize = 10; + + @Schema(description = "起始编号") + Integer startRow; + @Schema(description = "结束编号") + Integer endRow; + @Schema(description = "总页数") + Integer pages; + + @Schema(description = "内容列表") + List list; + + public Page() { + + } + + public Page(Integer pageNum, Integer pageSize) { + this.setPageNum(pageNum); + this.setPageSize(pageSize); + } + + /** + * 清空List + */ + public void clearList() { + list = new ArrayList<>(); + } + + public Long getTotal() { + return total; + } + + public void setTotal(Long total) { + this.total = total; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public Integer getStartRow() { + return startRow; + } + + public void setStartRow(Integer startRow) { + this.startRow = startRow; + } + + public Integer getEndRow() { + return endRow; + } + + public void setEndRow(Integer endRow) { + this.endRow = endRow; + } + + public Integer getPages() { + return pages; + } + + public void setPages(Integer pages) { + this.pages = pages; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/Sort.java b/lib/jpaHelper/src/main/java/com/cym/bean/Sort.java new file mode 100644 index 0000000..1835994 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/Sort.java @@ -0,0 +1,108 @@ +package com.cym.bean; + +import java.util.ArrayList; +import java.util.List; + +import com.cym.bean.OrderBy.Direction; +import com.cym.reflection.ReflectionUtil; +import com.cym.reflection.SerializableFunction; +import cn.hutool.core.util.StrUtil; + +public class Sort { + List orderList = new ArrayList<>(); + + public Sort() { + + } + + public Sort(String column, Direction direction) { + OrderBy order = new OrderBy(); + order.setColumn(column); + order.setDirection(direction); + + orderList.add(order); + } + + public Sort(List orderList) { + this.orderList.addAll(orderList); + } + + public Sort(String orderByStr) { + OrderBy order = new OrderBy(); + order.setOrderByStr(orderByStr); + + orderList.add(order); + } + + public Sort(SerializableFunction column, Direction direction) { + OrderBy order = new OrderBy(); + order.setColumn(ReflectionUtil.getFieldName(column)); + order.setDirection(direction); + + orderList.add(order); + } + + public Sort add(String column, Direction direction) { + OrderBy order = new OrderBy(); + order.setColumn(column); + order.setDirection(direction); + + orderList.add(order); + + return this; + } + + public Sort add(SerializableFunction column, Direction direction) { + OrderBy order = new OrderBy(); + order.setColumn(ReflectionUtil.getFieldName(column)); + order.setDirection(direction); + + orderList.add(order); + + return this; + } + + public Sort add(String orderByStr) { + OrderBy order = new OrderBy(); + order.setOrderByStr(orderByStr); + + orderList.add(order); + + return this; + } + + public String toString() { + List sqlList = new ArrayList<>(); + for (OrderBy order : orderList) { + if (StrUtil.isEmpty(order.getOrderByStr())) { + String sql = "`" + StrUtil.toUnderlineCase(order.getColumn()) + "`"; + + if (order.getDirection() == Direction.ASC) { + sql += " ASC"; + } + if (order.getDirection() == Direction.DESC) { + sql += " DESC"; + } + + sqlList.add(sql); + } else { + sqlList.add(order.getOrderByStr()); + } + } + if (sqlList.size() > 0) { + return " ORDER BY " + StrUtil.join(",", sqlList); + } else { + return ""; + } + + } + + public List getOrderList() { + return orderList; + } + + public void setOrderList(List orderList) { + this.orderList = orderList; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/Update.java b/lib/jpaHelper/src/main/java/com/cym/bean/Update.java new file mode 100644 index 0000000..d79722b --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/Update.java @@ -0,0 +1,35 @@ +package com.cym.bean; + +import java.util.HashMap; +import java.util.Map; + +import com.cym.reflection.ReflectionUtil; +import com.cym.reflection.SerializableFunction; + +public class Update { + + Map sets; + + public Update() { + sets = new HashMap(); + } + + public Update set(String key, Object value) { + sets.put(key, value); + return this; + } + + public Update set(SerializableFunction property, Object value) { + sets.put(ReflectionUtil.getFieldName(property), value); + return this; + } + + public Map getSets() { + return sets; + } + + public void setSets(Map sets) { + this.sets = sets; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/bean/UpdateTime.java b/lib/jpaHelper/src/main/java/com/cym/bean/UpdateTime.java new file mode 100644 index 0000000..fa243b1 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/bean/UpdateTime.java @@ -0,0 +1,12 @@ +package com.cym.bean; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface UpdateTime { + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/reflection/ReflectionUtil.java b/lib/jpaHelper/src/main/java/com/cym/reflection/ReflectionUtil.java new file mode 100644 index 0000000..91d3e80 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/reflection/ReflectionUtil.java @@ -0,0 +1,65 @@ +package com.cym.reflection; + +import java.beans.Introspector; +import java.lang.invoke.SerializedLambda; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +public class ReflectionUtil { + + private static Map, Field> cache = new ConcurrentHashMap<>(); + + public static String getFieldName(SerializableFunction function) { + Field field = ReflectionUtil.getField(function); + return field.getName(); + } + + public static Field getField(SerializableFunction function) { + return cache.computeIfAbsent(function, ReflectionUtil::findField); + } + + public static Field findField(SerializableFunction function) { + Field field = null; + String fieldName = null; + try { + // 第1步 获取SerializedLambda + Method method = function.getClass().getDeclaredMethod("writeReplace"); + method.setAccessible(Boolean.TRUE); + SerializedLambda serializedLambda = (SerializedLambda) method.invoke(function); + // 第2步 implMethodName 即为Field对应的Getter方法名 + String implMethodName = serializedLambda.getImplMethodName(); + if (implMethodName.startsWith("get") && implMethodName.length() > 3) { + fieldName = Introspector.decapitalize(implMethodName.substring(3)); + + } else if (implMethodName.startsWith("is") && implMethodName.length() > 2) { + fieldName = Introspector.decapitalize(implMethodName.substring(2)); + } else if (implMethodName.startsWith("lambda$")) { + throw new IllegalArgumentException("SerializableFunction不能传递lambda表达式,只能使用方法引用"); + + } else { + throw new IllegalArgumentException(implMethodName + "不是Getter方法引用"); + } + // 第3步 获取的Class是字符串,并且包名是“/”分割,需要替换成“.”,才能获取到对应的Class对象 + String declaredClass = serializedLambda.getImplClass().replace("/", "."); + Class aClass = Class.forName(declaredClass, false, ClassUtils.getDefaultClassLoader()); + + // 第4步 Spring 中的反射工具类获取Class中定义的Field + field = ReflectionUtils.findField(aClass, fieldName); + + } catch (Exception e) { + e.printStackTrace(); + } + // 第5步 如果没有找到对应的字段应该抛出异常 + if (field != null) { + return field; + } + throw new NoSuchFieldError(fieldName); + } + + +} \ No newline at end of file diff --git a/lib/jpaHelper/src/main/java/com/cym/reflection/SerializableFunction.java b/lib/jpaHelper/src/main/java/com/cym/reflection/SerializableFunction.java new file mode 100644 index 0000000..4a3bb6d --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/reflection/SerializableFunction.java @@ -0,0 +1,9 @@ +package com.cym.reflection; + +import java.io.Serializable; +import java.util.function.Function; + +@FunctionalInterface +public interface SerializableFunction extends Function, Serializable { + +} \ No newline at end of file diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/BeanExtUtil.java b/lib/jpaHelper/src/main/java/com/cym/utils/BeanExtUtil.java new file mode 100644 index 0000000..9952ed3 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/BeanExtUtil.java @@ -0,0 +1,58 @@ +package com.cym.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.cym.bean.Page; +import cn.hutool.core.bean.BeanUtil; + +public class BeanExtUtil { + + /** + * 根据List对象属性批量创建对应的Class List对象 + * + * @param list + * @param clazz + * @return + */ + public static List copyListByProperties(List list, Class clazz) { + if (list == null) { + return null; + } + + List rsList = new ArrayList<>(); + for (Object source : list) { + rsList.add((T) BeanUtil.copyProperties(source, clazz)); + } + + return rsList; + } + + + /** + * 根据PageResp对象属性批量创建对应的Class PageResp对象 + * + * @param pageResp + * @param clazz + * @return + */ + @SuppressWarnings("unchecked") + public static Page copyPageByProperties(Page page, Class clazz) { + Page pageNew = copyBeanByProperties(page, Page.class); + pageNew.setList(copyListByProperties(page.getList(), clazz)); + return pageNew; + } + + /** + * 按照Bean对象属性创建对应的Class对象 + * + */ + public static T copyBeanByProperties(Object source, Class tClass) { + return BeanUtil.copyProperties(source, tClass); + } + + + + + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/Condition.java b/lib/jpaHelper/src/main/java/com/cym/utils/Condition.java new file mode 100644 index 0000000..784a916 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/Condition.java @@ -0,0 +1,53 @@ +package com.cym.utils; + +public class Condition { + public Condition(String column, String operation, Object value) { + this.column = column; + this.operation = operation; + this.value = value; + } + + public Condition(String condition) { + this.condition = condition; + } + + String column; + String operation; + Object value; + String condition; + + + + public String getCondition() { + return condition; + } + + public void setCondition(String condition) { + this.condition = condition; + } + + public String getColumn() { + return column; + } + + public void setColumn(String column) { + this.column = column; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/ConditionAndWrapper.java b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionAndWrapper.java new file mode 100644 index 0000000..cb9942a --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionAndWrapper.java @@ -0,0 +1,351 @@ +package com.cym.utils; + +import java.util.Arrays; +import java.util.Collection; + +import com.cym.reflection.ReflectionUtil; +import com.cym.reflection.SerializableFunction; + +/** + * 查询语句生成器 AND连接 + * + */ +public class ConditionAndWrapper extends ConditionWrapper { + + public ConditionAndWrapper() { + andLink = true; + } + + public ConditionAndWrapper and(ConditionWrapper conditionWrapper) { + list.add(conditionWrapper); + return this; + } + + /** + * 自由撰写条件 + * + * @param condition 条件 + * @return ConditionWrapper + */ + public ConditionAndWrapper custom(String condition) { + super.custom(condition); + return this; + } + + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionAndWrapper eq(String column, Object params) { + super.eq(column, params); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionAndWrapper eq(SerializableFunction column, Object params) { + super.eq(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper ne(String column, Object params) { + super.ne(column, params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper ne(SerializableFunction column, Object params) { + super.ne(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lt(String column, Object params) { + super.lt(column, params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lt(SerializableFunction column, Object params) { + super.lt(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lte(String column, Object params) { + super.lte(column, params); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lte(SerializableFunction column, Object params) { + super.lte(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gt(String column, Object params) { + super.gt(column, params); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gt(SerializableFunction column, Object params) { + super.gt(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gte(String column, Object params) { + super.gte(column, params); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gte(SerializableFunction column, Object params) { + super.gte(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper like(String column, String params) { + super.like(column, params); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper like(SerializableFunction column, String params) { + super.like(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(String column, Collection params) { + super.in(column, params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(SerializableFunction column, Collection params) { + super.in(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(String column, Object[] params) { + super.in(column, Arrays.asList(params)); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(SerializableFunction column, Object[] params) { + super.in(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(String column, Collection params) { + super.nin(column, params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(SerializableFunction column, Collection params) { + super.nin(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(String column, Object[] params) { + super.nin(column, Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(SerializableFunction column, Object[] params) { + super.nin(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNull(String column) { + super.isNull(column); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNull(SerializableFunction column) { + super.isNull(ReflectionUtil.getFieldName(column)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNotNull(String column) { + super.isNotNull(column); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNotNull(SerializableFunction column) { + super.isNotNull(ReflectionUtil.getFieldName(column)); + return this; + } +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/ConditionOrWrapper.java b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionOrWrapper.java new file mode 100644 index 0000000..9a3e887 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionOrWrapper.java @@ -0,0 +1,332 @@ +package com.cym.utils; + +import java.util.Arrays; +import java.util.Collection; + +import com.cym.reflection.ReflectionUtil; +import com.cym.reflection.SerializableFunction; + +/** + * 查询语句生成器 OR连接 + * + */ +public class ConditionOrWrapper extends ConditionWrapper { + + public ConditionOrWrapper() { + andLink = false; + } + + public ConditionOrWrapper or(ConditionWrapper conditionWrapper) { + list.add(conditionWrapper); + return this; + } + + /** + * 自由撰写条件 + * + * @param condition 条件 + * @return ConditionWrapper + */ + public ConditionOrWrapper custom(String condition) { + super.custom(condition); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionOrWrapper eq(String column, Object params) { + super.eq(column, params); + return this; + } + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionOrWrapper eq(SerializableFunction column, Object params) { + super.eq(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper ne(String column, Object params) { + super.ne(column, params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper ne(SerializableFunction column, Object params) { + super.ne(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lt(String column, Object params) { + super.lt(column, params); + return this; + } + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lt(SerializableFunction column, Object params) { + super.lt(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lte(String column, Object params) { + super.lte(column, params); + return this; + } + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lte(SerializableFunction column, Object params) { + super.lte(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gt(String column, Object params) { + super.gt(column, params); + return this; + } + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gt(SerializableFunction column, Object params) { + super.gt(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gte(String column, Object params) { + super.gte(column, params); + return this; + } + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gte(SerializableFunction column, Object params) { + super.gte(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper like(String column, String params) { + super.like(column, params); + return this; + } + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper like(SerializableFunction column, String params) { + super.like(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(String column, Collection params) { + super.in(column, params); + return this; + } + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(SerializableFunction column, Collection params) { + super.in(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(String column, Object[] params) { + super.in(column, Arrays.asList(params)); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(SerializableFunction column, Object[] params) { + super.in(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(String column, Collection params) { + super.nin(column, params); + return this; + } + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(SerializableFunction column, Collection params) { + super.nin(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(String column, Object[] params) { + super.nin(column, Arrays.asList(params)); + return this; + } + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(SerializableFunction column, Object[] params) { + super.nin(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNull(String column) { + super.isNull(column); + return this; + } + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNull(SerializableFunction column) { + super.isNull(ReflectionUtil.getFieldName(column)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNotNull(String column) { + super.isNotNull(column); + return this; + } + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNotNull(SerializableFunction column) { + super.isNotNull(ReflectionUtil.getFieldName(column)); + return this; + } +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/ConditionWrapper.java b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionWrapper.java new file mode 100644 index 0000000..6d7ed6c --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/ConditionWrapper.java @@ -0,0 +1,247 @@ +package com.cym.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import cn.hutool.core.util.StrUtil; + +/** + * 查询语句生成器 + * + * @author CYM + * + */ +public abstract class ConditionWrapper { + boolean andLink; + + List list = new ArrayList(); + + /** + * 将Wrapper转化为Condition + * + * @param params + * + * @return Condition + */ + public String build(List values) { + String sql = ""; + if (list.size() > 0) { + List blocks = new ArrayList(); + for (Object object : list) { + if (object instanceof Condition) { + Condition condition = (Condition) object; + + if (StrUtil.isNotEmpty(condition.getCondition())) { + blocks.add(condition.getCondition()); + } else { + String block = null; + if (condition.getValue() == null) { + if (condition.getOperation().equals("IS NULL") || condition.getOperation().equals("IS NOT NULL")) { + block = buildColumn(condition.getColumn()) + " " + condition.getOperation(); + } else { + block = buildColumn(condition.getColumn()) + " " + condition.getOperation() + " null"; + } + } else { + if (condition.getValue() instanceof List) { + block = buildColumn(condition.getColumn()) + " " + condition.getOperation() + " " + buildIn(condition.getValue()); + for (Object val : (List) condition.getValue()) { + values.add(val); + } + } else { + block = buildColumn(condition.getColumn()) + " " + condition.getOperation() + " ?"; + if (!condition.getOperation().equals("LIKE")) { + values.add(condition.getValue()); + } else { + values.add("%" + condition.getValue().toString().replace("%", "\\%") + "%"); + } + } + } + blocks.add(block); + } + } + + if (object instanceof ConditionWrapper) { + ConditionWrapper conditionWrapper = (ConditionWrapper) object; + String block = " (" + conditionWrapper.build(values) + ") "; + blocks.add(block); + } + } + + if (andLink) { + sql = StrUtil.join(" AND ", blocks); + } else { + sql = StrUtil.join(" OR ", blocks); + } + + } + return sql; + } + + public String buildColumn(String column) { + return "`" + StrUtil.toUnderlineCase(column) + "`"; + } + + public String buildIn(Object value) { + List ask = new ArrayList(); + for (Object obj : (Collection) value) { + ask.add("?"); + } + + if (ask.size() > 0) { + return " (" + StrUtil.join(",", ask) + ") "; + } else { + return " (null) "; + } + + } + + /** + * 自由撰写条件 + * + * @param condition + */ + public ConditionWrapper custom(String condition) { + list.add(new Condition(condition)); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper eq(String column, Object params) { + list.add(new Condition(column, "=", params)); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper ne(String column, Object params) { + list.add(new Condition(column, "<>", params)); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper lt(String column, Object params) { + list.add(new Condition(column, "<", params)); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper lte(String column, Object params) { + list.add(new Condition(column, "<=", params)); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper gt(String column, Object params) { + list.add(new Condition(column, ">", params)); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper gte(String column, Object params) { + list.add(new Condition(column, ">=", params)); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper like(String column, String params) { + list.add(new Condition(column, "LIKE", params)); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper in(String column, Collection params) { + list.add(new Condition(column, "IN", params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper nin(String column, Collection params) { + list.add(new Condition(column, "NOT IN", params)); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionWrapper + */ + public ConditionWrapper isNull(String column) { + list.add(new Condition(column, "IS NULL", null)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionWrapper + */ + public ConditionWrapper isNotNull(String column) { + list.add(new Condition(column, "IS NOT NULL", null)); + return this; + } + + public boolean notEmpty() { + return list.size() > 0; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/InitTool.java b/lib/jpaHelper/src/main/java/com/cym/utils/InitTool.java new file mode 100644 index 0000000..0c1e5e4 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/InitTool.java @@ -0,0 +1,83 @@ +package com.cym.utils; + +import java.lang.reflect.Field; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.cym.bean.InitValue; +import com.cym.bean.Update; + +import cn.hutool.core.util.ClassUtil; +import cn.hutool.core.util.ReflectUtil; +import jakarta.persistence.Entity; +import jakarta.transaction.Transactional; + +@Service +public class InitTool { + @Autowired + PackageTools packageTools; + + @Autowired + JpaHelper jpaHelper; + + @Autowired + JdbcTemplate jdbcTemplate; + + @Value("${spring.datasource.url:}") + String url; + + @Transactional + public void init() { + Set> set = ClassUtil.scanPackage(packageTools.getMainPackage()); + // 注入默认值 + for (Class clazz : set) { + Entity entity = clazz.getAnnotation(Entity.class); + if (entity != null) { + Field[] fields = ReflectUtil.getFields(clazz); + for (Field field : fields) { + if (field.isAnnotationPresent(InitValue.class)) { + InitValue defaultValue = field.getAnnotation(InitValue.class); + if (defaultValue.value() != null) { + // 更新默认值 + Long count = jpaHelper.findCountByQuery(new ConditionAndWrapper().isNull(field.getName()), clazz); + if (count > 0) { + String value = defaultValue.value(); + Object obj = null; + // 获取字段类型 + Class type = field.getType(); + if (type.equals(String.class)) { + obj = value; + } + if (type.equals(Short.class)) { + obj = Short.parseShort(value); + } + if (type.equals(Integer.class)) { + obj = Integer.parseInt(value); + } + if (type.equals(Long.class)) { + obj = Long.parseLong(value); + } + if (type.equals(Float.class)) { + obj = Float.parseFloat(value); + } + if (type.equals(Double.class)) { + obj = Double.parseDouble(value); + } + if (type.equals(Boolean.class)) { + obj = Boolean.parseBoolean(value); + } + + jpaHelper.updateByQuery(new ConditionAndWrapper().isNull(field.getName()), new Update().set(field.getName(), obj), clazz); + } + } + } + } + } + } + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/InitUtil.java b/lib/jpaHelper/src/main/java/com/cym/utils/InitUtil.java new file mode 100644 index 0000000..664b3d3 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/InitUtil.java @@ -0,0 +1,17 @@ +package com.cym.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; + +import jakarta.annotation.PostConstruct; + +@Configuration +public class InitUtil { + @Autowired + InitTool initTool; + + @PostConstruct + public void init() { + initTool.init(); + } +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/JpaHelper.java b/lib/jpaHelper/src/main/java/com/cym/utils/JpaHelper.java new file mode 100644 index 0000000..0c7270d --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/JpaHelper.java @@ -0,0 +1,1018 @@ +package com.cym.utils; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.cym.bean.CreateTime; +import com.cym.bean.InitValue; +import com.cym.bean.Page; +import com.cym.bean.Sort; +import com.cym.bean.Update; +import com.cym.bean.UpdateTime; +import com.cym.reflection.ReflectionUtil; +import com.cym.reflection.SerializableFunction; + +import cn.hutool.core.util.ReflectUtil; +import cn.hutool.core.util.StrUtil; +import jakarta.persistence.Id; + +/** + * sql操作器 + * + */ +@Service +public class JpaHelper { + Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + JdbcTemplate jdbcTemplate; + + @Value("${spring.datasource.url:}") + String url; + @Autowired + SqlUtils sqlUtils; + + /** + * 获取主键 + * + * @param clazz + * @return + */ + public String getPrimalKey(Class clazz) { + + Field[] fields = ReflectUtil.getFields(clazz); + + for (Field field : fields) { + if (field.isAnnotationPresent(Id.class)) { + return field.getName(); + } + } + + return null; + } + + /** + * 获取主键值 + * + * @param clazz + * @return + */ + public String getPrimalValue(Object object) { + String key = getPrimalKey(object.getClass()); + + if (StrUtil.isNotEmpty(key)) { + Object obj = ReflectUtil.getFieldValue(object, key); + return obj != null ? obj.toString() : null; + } + return null; + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + + public void addCountById(String id, SerializableFunction property, Long count, Class clazz) { + addCountById(id, ReflectionUtil.getFieldName(property), count, clazz); + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + + public void addCountById(String id, String property, Long count, Class clazz) { + String sql = "UPDATE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` SET `" + StrUtil.toUnderlineCase(property) + "` = `" + StrUtil.toUnderlineCase(property) + + "` + ? WHERE `id` = ?"; + Object[] params = new Object[] { count, id }; + sqlUtils.logQuery(sql, params); + jdbcTemplate.update(buildSql(sql), params); + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + + public void addCountById(String id, SerializableFunction property, Double count, Class clazz) { + addCountById(id, ReflectionUtil.getFieldName(property), count, clazz); + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + + public void addCountById(String id, String property, Double count, Class clazz) { + String sql = "UPDATE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` SET `" + StrUtil.toUnderlineCase(property) + "` = `" + StrUtil.toUnderlineCase(property) + + "` + ? WHERE `id` = ?"; + Object[] params = new Object[] { count, id }; + sqlUtils.logQuery(sql, params); + jdbcTemplate.update(buildSql(sql), params); + } + + /** + * 插入或更新 + * + * @param object 对象 @throws + */ + + public String insertOrUpdate(Object object) { + Long time = System.currentTimeMillis(); + String id = getPrimalValue(object); + if (StrUtil.isEmpty(id)) { + // 插入 + // 设置插入时间 + setCreateTime(object, time); + // 设置更新时间 + setUpdateTime(object, time); + // 设置默认值 + setDefaultVaule(object); + // 设置id + ReflectUtil.setFieldValue(object, getPrimalKey(object.getClass()), SnowFlakeUtils.nextId()); + + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + List paramValues = new ArrayList(); + + List fields = getFields(object.getClass()); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + + String sql = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + sqlUtils.logQuery(sql, paramValues.toArray()); + jdbcTemplate.update(buildSql(sql), paramValues.toArray()); + + } else { + // 更新 + updateById(object); + } + + // 返回id + return getPrimalValue(object); + } + + /** + * 插入 + * + * @param object 对象 + */ + + public String insert(Object object) { + // 去除主键id + ReflectUtil.setFieldValue(object, getPrimalKey(object.getClass()), null); + + // 插入数据库 + insertOrUpdate(object); + + // 返回id + return getPrimalValue(object); + } + + /** + * 插入全部字段 + * + * @param object 对象 + */ + public String insertAllColumn(Object object) { + // 没有id生成id + String id = (String) ReflectUtil.getFieldValue(object, getPrimalKey(object.getClass())); + if (StrUtil.isEmpty(id)) { + id = SnowFlakeUtils.nextId().toString(); + ReflectUtil.setFieldValue(object, getPrimalKey(object.getClass()), id); + } + + String sql = ""; + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + List paramValues = new ArrayList(); + + List fields = getFields(object.getClass()); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + + sql = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + sqlUtils.logQuery(sql, paramValues.toArray()); + jdbcTemplate.update(buildSql(sql), paramValues.toArray()); + + // 返回id + return getPrimalValue(object); + } + + /** + * 批量插入 + * + * @param object 对象 + */ + public List insertBatch(List objectList) { + if (objectList == null || objectList.size() == 0) { + return new ArrayList<>(); + } + Long time = System.currentTimeMillis(); + List ids = new ArrayList<>(); + List paramValues = new ArrayList(); + + String sql = null; + for (Object object : objectList) { + // 设置插入时间 + setCreateTime(object, time); + // 设置更新时间 + setUpdateTime(object, time); + // 设置默认值 + setDefaultVaule(object); + + // 没有id生成id + String id = (String) ReflectUtil.getFieldValue(object, getPrimalKey(object.getClass())); + if (StrUtil.isEmpty(id)) { + id = SnowFlakeUtils.nextId().toString(); + ReflectUtil.setFieldValue(object, getPrimalKey(object.getClass()), id); + } + ids.add(id); + + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + List objs = new ArrayList<>(); + + List fields = getFields(object.getClass()); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + objs.add(ReflectUtil.getFieldValue(object, field)); + } + paramValues.add(objs.toArray()); + + if (sql == null) { + sql = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + } + + sqlUtils.logQuery(sql, objs.toArray()); + } + + jdbcTemplate.batchUpdate(buildSql(sql), paramValues); + // 返回id + return ids; + } + + /** + * 根据id更新 + * + * @param object 对象 + */ + + public void updateById(Object object) { + if (StrUtil.isEmpty(getPrimalValue(object))) { + return; + } + // 设置更新时间 + setUpdateTime(object, System.currentTimeMillis()); + + List fields = getFields(object.getClass()); + + List fieldsPart = new ArrayList(); + List paramValues = new ArrayList(); + + for (Field field : fields) { + if (!field.getName().equals(getPrimalKey(object.getClass())) && ReflectUtil.getFieldValue(object, field) != null) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`=?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + } + paramValues.add(getPrimalValue(object)); + if (fieldsPart.size() == 0) { + return; + } + String sql = "UPDATE `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart) + " WHERE id = ?"; + sqlUtils.logQuery(sql, paramValues.toArray()); + jdbcTemplate.update(buildSql(sql), paramValues.toArray()); + } + + /** + * 根据id更新全部字段 + * + * @param object 对象 + */ + + public void updateAllColumnById(Object object) { + if (StrUtil.isEmpty(getPrimalValue(object))) { + return; + } + + List fields = getFields(object.getClass()); + + List fieldsPart = new ArrayList(); + List paramValues = new ArrayList(); + + for (Field field : fields) { + if (!field.getName().equals(getPrimalKey(object.getClass()))) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`=?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + } + paramValues.add(getPrimalValue(object)); + + String sql = "UPDATE `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart) + " WHERE id = ?"; + sqlUtils.logQuery(sql, paramValues.toArray()); + jdbcTemplate.update(buildSql(sql), paramValues.toArray()); + } + + /** + * 条件更新 + * + * @param conditionAndWrapper + * @param update + * @param clazz + */ + + public void updateByQuery(ConditionWrapper conditionWrapper, Update update, Class clazz) { + if (update == null || update.getSets().size() == 0) { + return; + } + + List fieldsPart = new ArrayList(); + List values = new ArrayList(); + for (Entry entry : update.getSets().entrySet()) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(entry.getKey()) + "`=?"); + values.add(entry.getValue()); + } + + String sql = "UPDATE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart); + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + sqlUtils.logQuery(sql, values.toArray()); + jdbcTemplate.update(buildSql(sql), values.toArray()); + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + + public void deleteById(String id, Class clazz) { + if (StrUtil.isEmpty(id)) { + return; + } + + deleteByQuery(new ConditionAndWrapper().eq(getPrimalKey(clazz), id), clazz); + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + + public void deleteByIds(Collection ids, Class clazz) { + if (ids == null || ids.size() == 0) { + return; + } + deleteByQuery(new ConditionAndWrapper().in(getPrimalKey(clazz), ids), clazz); + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + + public void deleteByIds(String[] ids, Class clazz) { + deleteByQuery(new ConditionAndWrapper().in(getPrimalKey(clazz), ids), clazz); + } + + /** + * 根据条件删除 + * + * @param query 查询 + * @param clazz 类 + */ + + public void deleteByQuery(ConditionWrapper conditionWrapper, Class clazz) { + + List values = new ArrayList(); + String sql = "DELETE FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + sqlUtils.logQuery(sql, values.toArray()); + jdbcTemplate.update(buildSql(sql), values.toArray()); + } + + /** + * 设置默认值 + * + * @param object 对象 + */ + public void setDefaultVaule(Object object) { + List fields = getFields(object.getClass()); + for (Field field : fields) { + // 获取注解 + if (field.isAnnotationPresent(InitValue.class)) { + InitValue defaultValue = field.getAnnotation(InitValue.class); + + String value = defaultValue.value(); + + if (ReflectUtil.getFieldValue(object, field) == null) { + // 获取字段类型 + Class type = field.getType(); + if (type.equals(String.class)) { + ReflectUtil.setFieldValue(object, field, value); + } + if (type.equals(Short.class)) { + ReflectUtil.setFieldValue(object, field, Short.parseShort(value)); + } + if (type.equals(Integer.class)) { + ReflectUtil.setFieldValue(object, field, Integer.parseInt(value)); + } + if (type.equals(Long.class)) { + ReflectUtil.setFieldValue(object, field, Long.parseLong(value)); + } + if (type.equals(Float.class)) { + ReflectUtil.setFieldValue(object, field, Float.parseFloat(value)); + } + if (type.equals(Double.class)) { + ReflectUtil.setFieldValue(object, field, Double.parseDouble(value)); + } + if (type.equals(Boolean.class)) { + ReflectUtil.setFieldValue(object, field, Boolean.parseBoolean(value)); + } + } + } + } + } + + /** + * 设置更新时间 + * + * @param object 对象 + */ + public void setUpdateTime(Object object, Long time) { + List fields = getFields(object.getClass()); + for (Field field : fields) { + // 获取注解 + if (field.isAnnotationPresent(UpdateTime.class) && field.getType().equals(Long.class)) { + ReflectUtil.setFieldValue(object, field, time); + } + } + } + + /** + * 设置创建时间 + * + * @param object 对象 + */ + public void setCreateTime(Object object, Long time) { + List fields = getFields(object.getClass()); + for (Field field : fields) { + // 获取注解 + if (field.isAnnotationPresent(CreateTime.class) && field.getType().equals(Long.class)) { + ReflectUtil.setFieldValue(object, field, time); + } + } + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPageByQuery(ConditionWrapper conditionWrapper, Sort sort, Page page, Class clazz) { + List values = new ArrayList(); + // 查询出一共的条数 + Long count = findCountByQuery(conditionWrapper, clazz); + + String sql = "SELECT * FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + if (sort != null && sort.getOrderList().size() > 0) { + sql += " " + sort.toString(); + } else { + sql += " ORDER BY " + getPrimalKey(clazz) + " DESC"; + } + + sql += buildLimit(page); + + Page pageResp = new Page<>(); + pageResp.setPageSize(page.getPageSize()); + pageResp.setPageNum(page.getPageNum()); + pageResp.setTotal(count); + + pageResp.setStartRow((page.getPageNum() - 1) * page.getPageNum() + 1); + pageResp.setEndRow(pageResp.getStartRow() + page.getPageSize() - 1); + pageResp.setPages((count.intValue() + page.getPageSize() - 1) / page.getPageSize()); + + sqlUtils.logQuery(sql, values.toArray()); + pageResp.setList(buildObjects(jdbcTemplate.queryForList(buildSql(sql), values.toArray()), clazz)); + + return pageResp; + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPageByQuery(Sort sort, Page page, Class clazz) { + return findPageByQuery(null, sort, page, clazz); + } + + /** + * 按查询条件获取Page + * + * @param + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPageByQuery(ConditionWrapper conditionWrapper, Page page, Class clazz) { + return findPageByQuery(conditionWrapper, null, page, clazz); + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPageByQuery(Page page, Class clazz) { + return findPageByQuery(null, null, page, clazz); + } + + /** + * 根据id查找 + * + * @param id id + * @param clazz 类 + * @return T 对象 + */ + public T findById(String id, Class clazz) { + if (StrUtil.isEmpty(id)) { + return null; + } + + return findOneByQuery(new ConditionAndWrapper().eq(getPrimalKey(clazz), id), clazz); + + } + + /** + * 根据条件查找单个 + * + * @param query 查询 + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(ConditionWrapper conditionWrapper, Sort sort, Class clazz) { + + Page page = new Page(); + page.setPageSize(1); + page.setPageNum(1); + Page pageResp = findPageByQuery(conditionWrapper, sort, page, clazz); + + if (pageResp.getList().size() > 0) { + return pageResp.getList().get(0); + + } + return null; + } + + /** + * 根据条件查找单个 + * + * @param query 查询 + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(Sort sort, Class clazz) { + return findOneByQuery(null, sort, clazz); + } + + /** + * 根据条件查找单个 + * + * @param 类型 + * @param condition + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(ConditionWrapper conditionWrapper, Class clazz) { + return findOneByQuery(conditionWrapper, null, clazz); + + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param query 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(ConditionWrapper conditionWrapper, Sort sort, Class clazz) { + List values = new ArrayList(); + + String sql = "SELECT * FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + if (sort != null) { + sql += " " + sort.toString(); + } else { + sql += " ORDER BY `" + getPrimalKey(clazz) + "` DESC"; + } + sqlUtils.logQuery(sql, values.toArray()); + return buildObjects(jdbcTemplate.queryForList(buildSql(sql), values.toArray()), clazz); + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(ConditionWrapper conditionWrapper, Class clazz) { + return (List) findListByQuery(conditionWrapper, null, clazz); + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(Sort sort, Class clazz) { + return (List) findListByQuery(null, sort, clazz); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param query 查询 + * @param clazz 类 + * @param property 属性 + * @param propertyClass 属性类 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class clazz, String property, Class propertyClass) { + List list = findListByQuery(conditionWrapper, clazz); + List propertyList = extractProperty(list, property, propertyClass); + + return propertyList; + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param query 查询 + * @param clazz 类 + * @param property 属性 + * @param propertyClass 属性类 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class clazz, SerializableFunction property, Class propertyClass) { + return findPropertiesByQuery(conditionWrapper, clazz, ReflectionUtil.getFieldName(property), propertyClass); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class clazz, String property) { + return findPropertiesByQuery(conditionWrapper, clazz, property, String.class); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class clazz, SerializableFunction property) { + return findPropertiesByQuery(conditionWrapper, clazz, ReflectionUtil.getFieldName(property), String.class); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(Collection ids, Class clazz, String property) { + if (ids == null || ids.size() == 0) { + return new ArrayList(); + } + + ConditionAndWrapper ConditionAndWrapper = new ConditionAndWrapper(); + ConditionAndWrapper.in(getPrimalKey(clazz), ids); + + return findPropertiesByQuery(ConditionAndWrapper, clazz, property, String.class); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(Collection ids, Class clazz, SerializableFunction property) { + return findPropertiesByIds(ids, clazz, ReflectionUtil.getFieldName(property)); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(String[] ids, Class clazz, String property) { + return findPropertiesByIds(Arrays.asList(ids), clazz, property); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(String[] ids, Class clazz, SerializableFunction property) { + return findPropertiesByIds(Arrays.asList(ids), clazz, ReflectionUtil.getFieldName(property)); + } + + /** + * 根据条件查找id + * + * @param query 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findIdsByQuery(ConditionWrapper conditionWrapper, Class clazz) { + + return findPropertiesByQuery(conditionWrapper, clazz, getPrimalKey(clazz)); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(Collection ids, Class clazz) { + return findListByIds(ids, null, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(String[] ids, Class clazz) { + return findListByIds(Arrays.asList(ids), null, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(Collection ids, Sort sort, Class clazz) { + if (ids == null || ids.size() == 0) { + return new ArrayList(); + } + + ConditionAndWrapper ConditionAndWrapper = new ConditionAndWrapper(); + ConditionAndWrapper.in(getPrimalKey(clazz), ids); + + return findListByQuery(ConditionAndWrapper, sort, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(String[] ids, Sort sort, Class clazz) { + return findListByIds(Arrays.asList(ids), sort, clazz); + } + + /** + * 查询全部 + * + * @param 类型 + * @param clazz 类 + * @return List 列表 + */ + public List findAll(Class clazz) { + return findAll(null, clazz); + } + + /** + * 查询全部 + * + * @param 类型 + * @param clazz 类 + * @return List 列表 + */ + public List findAll(Sort sort, Class clazz) { + return findListByQuery(null, sort, clazz); + } + + /** + * 查找全部的id + * + * @param clazz 类 + * @return List 列表 + */ + public List findAllIds(Class clazz) { + return findIdsByQuery(null, clazz); + } + + /** + * 查找数量 + * + * @param condition 查询 + * @param clazz 类 + * @return Long 数量 + */ + public Long findCountByQuery(ConditionWrapper conditionWrapper, Class clazz) { + List values = new ArrayList(); + String sql = "SELECT COUNT(*) FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + sqlUtils.logQuery(sql, values.toArray()); + return jdbcTemplate.queryForObject(buildSql(sql), Long.class, values.toArray()); + } + + /** + * 查找全部数量 + * + * @param clazz 类 + * @return Long 数量 + */ + public Long findAllCount(Class clazz) { + return findCountByQuery(null, clazz); + } + + /** + * 获取list中对象某个属性,组成新的list + * + * @param list 列表 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + public List extractProperty(List list, String property, Class clazz) { + Set rs = new HashSet(); + for (Object object : list) { + Object value = ReflectUtil.getFieldValue(object, property); + if (value != null && value.getClass().equals(clazz)) { + rs.add((T) value); + } + } + + return new ArrayList(rs); + } + + /** + * Map转Bean + * + * @param + * @param queryForList + * @param clazz + * @return + */ + public List buildObjects(List> queryForList, Class clazz) { + List list = new ArrayList(); + try { + Field[] fields = ReflectUtil.getFields(clazz); + + for (Map map : queryForList) { + Object obj = clazz.getDeclaredConstructor().newInstance(); + + for (Map.Entry entry : map.entrySet()) { + String mapKey = entry.getKey(); + Object mapValue = entry.getValue(); + + for (Field field : fields) { + if (StrUtil.toUnderlineCase(field.getName()).equals(mapKey)) { + ReflectUtil.setFieldValue(obj, field.getName(), mapValue); + break; + } + } + + } + + list.add((T) obj); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return list; + } + + public String buildSql(String sql) { + if (StrUtil.isEmpty(sql)) { + return ""; + } + + if (!url.contains("mysql")) { + sql = sql.replace("`", "\""); + } + + return sql; + } + + public String buildLimit(Page page) { + if (url.contains("mysql") || url.contains("sqlite")) { + return " LIMIT " + (page.getPageNum() - 1) * page.getPageSize() + "," + page.getPageSize(); + } else { + return " LIMIT " + page.getPageSize() + " OFFSET " + (page.getPageNum() - 1) * page.getPageSize(); + } + } + + public List getFields(Class clazz) { + + Field[] fields = ReflectUtil.getFields(clazz); + List list = new ArrayList<>(); + for (Field field : fields) { + if (!field.toString().contains("static") && !field.toString().contains("final")) { + list.add(field); + } + } + + return list; + } + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/PackageTools.java b/lib/jpaHelper/src/main/java/com/cym/utils/PackageTools.java new file mode 100644 index 0000000..3be9dd5 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/PackageTools.java @@ -0,0 +1,28 @@ +package com.cym.utils; + +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +@Component +public class PackageTools { + + @Autowired + ApplicationContext context; + + /** + * 找到主程序包 + * @return + */ + public String getMainPackage() { + Map annotatedBeans = context.getBeansWithAnnotation(SpringBootApplication.class); + String packageName = annotatedBeans.isEmpty() ? null : annotatedBeans.values().toArray()[0].getClass().getPackage().getName(); + + return packageName; + } + + +} diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/SnowFlakeUtils.java b/lib/jpaHelper/src/main/java/com/cym/utils/SnowFlakeUtils.java new file mode 100644 index 0000000..b80b109 --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/SnowFlakeUtils.java @@ -0,0 +1,11 @@ +package com.cym.utils; + +import cn.hutool.core.util.IdUtil; + +public class SnowFlakeUtils { + + public static Long nextId() { + return IdUtil.getSnowflake(0, 0).nextId(); + } + +} \ No newline at end of file diff --git a/lib/jpaHelper/src/main/java/com/cym/utils/SqlUtils.java b/lib/jpaHelper/src/main/java/com/cym/utils/SqlUtils.java new file mode 100644 index 0000000..bf6ba1f --- /dev/null +++ b/lib/jpaHelper/src/main/java/com/cym/utils/SqlUtils.java @@ -0,0 +1,61 @@ +package com.cym.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import cn.hutool.core.util.StrUtil; + +@Component +public class SqlUtils { + Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Value("${spring.datasource.url:}") + String url; + + @Value("${spring.datasource.printsql:true}") + Boolean printsql; + + String separator = System.getProperty("line.separator"); + + public void logQuery(String sql) { + logQuery(sql, null); + } + + public void logQuery(String sql, Object[] params) { + sql = formatSql(sql); + + if (params != null) { + for (Object object : params) { + + if (object instanceof String) { + sql = sql.replaceFirst("\\?", "'" + object.toString().replace("$", "¥").replace("\\%", "\\\\%") + "'"); + } else { + sql = sql.replaceFirst("\\?", String.valueOf(object)); + } + + } + } + if (printsql) { + logger.info(separator + sql + separator); + } + } + + public String formatSql(String sql) { + if (StrUtil.isEmpty(sql)) { + return ""; + } + + if (!url.contains("mysql")) { + sql = sql.replace("`", "\""); + } + + sql = sql.replace("FROM", separator + "FROM")// + .replace("WHERE", separator + "WHERE")// + .replace("ORDER", separator + "ORDER")// + .replace("LIMIT", separator + "LIMIT")// + .replace("VALUES", separator + "VALUES");// + return sql; + } +} diff --git a/lib/sqlHelper/.gitignore b/lib/sqlHelper/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/lib/sqlHelper/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/lib/sqlHelper/pom.xml b/lib/sqlHelper/pom.xml new file mode 100644 index 0000000..ae77cc4 --- /dev/null +++ b/lib/sqlHelper/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + sqlHelper + jar + release + + org.springframework.boot + spring-boot-starter-parent + 3.3.3 + + + + + 21 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + org.xerial + sqlite-jdbc + + + + cn.hutool + hutool-all + 5.8.25 + + + + + io.swagger.core.v3 + swagger-annotations-jakarta + 2.2.19 + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + \ No newline at end of file diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/BaseModel.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/BaseModel.java new file mode 100644 index 0000000..f9657db --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/BaseModel.java @@ -0,0 +1,39 @@ +package com.cym.sqlHelper.bean; + +import java.io.Serializable; + +import io.swagger.v3.oas.annotations.media.Schema; + +public class BaseModel implements Serializable { + @Schema(description = "主键id") + String id; + @Schema(hidden = true) + Long createTime; + @Schema(hidden = true) + Long updateTime; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Long getCreateTime() { + return createTime; + } + + public void setCreateTime(Long createTime) { + this.createTime = createTime; + } + + public Long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Long updateTime) { + this.updateTime = updateTime; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Order.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Order.java new file mode 100644 index 0000000..72f7fcf --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Order.java @@ -0,0 +1,25 @@ +package com.cym.sqlHelper.bean; + +import com.cym.sqlHelper.bean.Sort.Direction; + +public class Order { + Direction direction; + String column; + + public Direction getDirection() { + return direction; + } + + public void setDirection(Direction direction) { + this.direction = direction; + } + + public String getColumn() { + return column; + } + + public void setColumn(String column) { + this.column = column; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Page.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Page.java new file mode 100644 index 0000000..ae13838 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Page.java @@ -0,0 +1,60 @@ +package com.cym.sqlHelper.bean; + +import java.util.Collections; +import java.util.List; + +import io.swagger.v3.oas.annotations.media.Schema; + +/** + * 分页类 + * + */ +public class Page { + @Schema(description ="总记录数") + Long count = 0l; + @Schema(description ="起始页(从1开始)") + Integer curr = 1; + + @Schema(description ="每页记录数") + Integer limit = 10; + + @Schema(description ="列表内容") + List records = Collections.emptyList(); + +// public List getRecords(Class clazz) { +// return (List) records; +// } + + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + public Long getCount() { + return count; + } + + public void setCount(Long count) { + this.count = count; + } + + public Integer getCurr() { + return curr; + } + + public void setCurr(Integer curr) { + this.curr = curr; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Sort.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Sort.java new file mode 100644 index 0000000..e8871c4 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Sort.java @@ -0,0 +1,83 @@ +package com.cym.sqlHelper.bean; + +import java.util.ArrayList; +import java.util.List; + +import com.cym.sqlHelper.reflection.ReflectionUtil; +import com.cym.sqlHelper.reflection.SerializableFunction; + +import cn.hutool.core.util.StrUtil; + +public class Sort { + List orderList = new ArrayList<>(); + + public static enum Direction { + ASC, DESC; + } + + public Sort() { + + } + + public Sort(String column, Direction direction) { + Order order = new Order(); + order.setColumn(column); + order.setDirection(direction); + + orderList.add(order); + } + + public Sort(List orderList) { + this.orderList.addAll(orderList); + } + + public Sort(SerializableFunction column, Direction direction) { + Order order = new Order(); + order.setColumn(ReflectionUtil.getFieldName(column)); + order.setDirection(direction); + + orderList.add(order); + } + + public Sort add(String column, Direction direction) { + Order order = new Order(); + order.setColumn(column); + order.setDirection(direction); + + orderList.add(order); + + return this; + } + + public Sort add(SerializableFunction column, Direction direction) { + Order order = new Order(); + order.setColumn(ReflectionUtil.getFieldName(column)); + order.setDirection(direction); + + orderList.add(order); + + return this; + } + + public String toString() { + List sqlList = new ArrayList<>(); + for (Order order : orderList) { + + String sql = StrUtil.toUnderlineCase(order.getColumn()); + + if (order.getDirection() == Direction.ASC) { + sql += " ASC"; + } + if (order.getDirection() == Direction.DESC) { + sql += " DESC"; + } + + sqlList.add(sql); + } + + return " ORDER BY " + StrUtil.join(",", sqlList); + } + + + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Update.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Update.java new file mode 100644 index 0000000..74a8bbd --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/bean/Update.java @@ -0,0 +1,27 @@ +package com.cym.sqlHelper.bean; + +import java.util.HashMap; +import java.util.Map; + +public class Update { + + Map sets; + + public Update() { + sets = new HashMap(); + } + + public Update set(String key, Object value) { + sets.put(key, value); + return this; + } + + public Map getSets() { + return sets; + } + + public void setSets(Map sets) { + this.sets = sets; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/AsyncConfig.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/AsyncConfig.java new file mode 100644 index 0000000..53f510b --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/AsyncConfig.java @@ -0,0 +1,24 @@ +package com.cym.sqlHelper.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +@Configuration +public class AsyncConfig { + + private static final int MAX_POOL_SIZE = 50; + + private static final int CORE_POOL_SIZE = 20; + + @Bean("sqlThreadPool") + public AsyncTaskExecutor sqlThreadPool() { + ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor(); + asyncTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE); + asyncTaskExecutor.setCorePoolSize(CORE_POOL_SIZE); + asyncTaskExecutor.setThreadNamePrefix("sql-thread-pool-"); + asyncTaskExecutor.initialize(); + return asyncTaskExecutor; + } +} \ No newline at end of file diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/CompositeIndex.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/CompositeIndex.java new file mode 100644 index 0000000..7c1f85a --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/CompositeIndex.java @@ -0,0 +1,15 @@ + +package com.cym.sqlHelper.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface CompositeIndex { + + boolean unique() default false; + String[] colums(); +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/DataSourceConfig.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/DataSourceConfig.java new file mode 100644 index 0000000..592ff82 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/DataSourceConfig.java @@ -0,0 +1,59 @@ +package com.cym.sqlHelper.config; + +import java.io.File; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.zaxxer.hikari.HikariDataSource; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.StrUtil; + +@Configuration +public class DataSourceConfig { + @Value("${spring.datasource.url:}") + String url; + @Value("${spring.datasource.username:}") + String username; + @Value("${spring.datasource.password:}") + String password; + @Value("${spring.database.type}") + String database; + + @Value("${spring.database.sqlite-path:}") + String sqlitePath; + + @Bean + public DataSource dataSource() throws Exception { + HikariDataSource dataSource = new HikariDataSource(); + if (database.toLowerCase().equals("mysql")) { + dataSource.setJdbcUrl(url); + dataSource.setUsername(username);// 用户名 + dataSource.setPassword(password);// 密码 + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + } else if (database.toLowerCase().equals("postgresql")) { + dataSource.setJdbcUrl(url); + dataSource.setUsername(username);// 用户名 + dataSource.setPassword(password);// 密码 + dataSource.setDriverClassName("org.postgresql.Driver"); + } else if (database.toLowerCase().equals("sqlite")) { + if (StrUtil.isEmpty(sqlitePath)) { + sqlitePath = FileUtil.getUserHomePath() + File.separator + "sqlite.db"; + } + + dataSource.setJdbcUrl("jdbc:sqlite:" + sqlitePath); + dataSource.setDriverClassName("org.sqlite.JDBC"); + + // sqlite使用连接池 + dataSource.setMaximumPoolSize(5); + } else { + throw new Exception("数据库类型配置错误"); + } + + return dataSource; + } +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/InitValue.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/InitValue.java new file mode 100644 index 0000000..b48cd67 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/InitValue.java @@ -0,0 +1,14 @@ +package com.cym.sqlHelper.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD }) +public @interface InitValue { + + String value(); + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/SingleIndex.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/SingleIndex.java new file mode 100644 index 0000000..53f9536 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/SingleIndex.java @@ -0,0 +1,15 @@ + +package com.cym.sqlHelper.config; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface SingleIndex { + + boolean unique() default false; + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/Table.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/Table.java new file mode 100644 index 0000000..cd55e05 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/config/Table.java @@ -0,0 +1,15 @@ +package com.cym.sqlHelper.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface Table { + + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/ReflectionUtil.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/ReflectionUtil.java new file mode 100644 index 0000000..1014a1f --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/ReflectionUtil.java @@ -0,0 +1,65 @@ +package com.cym.sqlHelper.reflection; + +import java.beans.Introspector; +import java.lang.invoke.SerializedLambda; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +public class ReflectionUtil { + + private static Map, Field> cache = new ConcurrentHashMap<>(); + + public static String getFieldName(SerializableFunction function) { + Field field = ReflectionUtil.getField(function); + return field.getName(); + } + + public static Field getField(SerializableFunction function) { + return cache.computeIfAbsent(function, ReflectionUtil::findField); + } + + public static Field findField(SerializableFunction function) { + Field field = null; + String fieldName = null; + try { + // 第1步 获取SerializedLambda + Method method = function.getClass().getDeclaredMethod("writeReplace"); + method.setAccessible(Boolean.TRUE); + SerializedLambda serializedLambda = (SerializedLambda) method.invoke(function); + // 第2步 implMethodName 即为Field对应的Getter方法名 + String implMethodName = serializedLambda.getImplMethodName(); + if (implMethodName.startsWith("get") && implMethodName.length() > 3) { + fieldName = Introspector.decapitalize(implMethodName.substring(3)); + + } else if (implMethodName.startsWith("is") && implMethodName.length() > 2) { + fieldName = Introspector.decapitalize(implMethodName.substring(2)); + } else if (implMethodName.startsWith("lambda$")) { + throw new IllegalArgumentException("SerializableFunction不能传递lambda表达式,只能使用方法引用"); + + } else { + throw new IllegalArgumentException(implMethodName + "不是Getter方法引用"); + } + // 第3步 获取的Class是字符串,并且包名是“/”分割,需要替换成“.”,才能获取到对应的Class对象 + String declaredClass = serializedLambda.getImplClass().replace("/", "."); + Class aClass = Class.forName(declaredClass, false, ClassUtils.getDefaultClassLoader()); + + // 第4步 Spring 中的反射工具类获取Class中定义的Field + field = ReflectionUtils.findField(aClass, fieldName); + + } catch (Exception e) { + e.printStackTrace(); + } + // 第5步 如果没有找到对应的字段应该抛出异常 + if (field != null) { + return field; + } + throw new NoSuchFieldError(fieldName); + } + + +} \ No newline at end of file diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/SerializableFunction.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/SerializableFunction.java new file mode 100644 index 0000000..69b35d0 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/reflection/SerializableFunction.java @@ -0,0 +1,9 @@ +package com.cym.sqlHelper.reflection; + +import java.io.Serializable; +import java.util.function.Function; + +@FunctionalInterface +public interface SerializableFunction extends Function, Serializable { + +} \ No newline at end of file diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/Condition.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/Condition.java new file mode 100644 index 0000000..b852b98 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/Condition.java @@ -0,0 +1,39 @@ +package com.cym.sqlHelper.utils; + +public class Condition { + public Condition(String column, String operation, Object value) { + this.column = column; + this.operation = operation; + this.value = value; + } + + String column; + String operation; + Object value; + + + public String getColumn() { + return column; + } + + public void setColumn(String column) { + this.column = column; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionAndWrapper.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionAndWrapper.java new file mode 100644 index 0000000..c773c3f --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionAndWrapper.java @@ -0,0 +1,339 @@ +package com.cym.sqlHelper.utils; + +import java.util.Arrays; +import java.util.Collection; + +import com.cym.sqlHelper.reflection.ReflectionUtil; +import com.cym.sqlHelper.reflection.SerializableFunction; + +/** + * 查询语句生成器 AND连接 + * + */ +public class ConditionAndWrapper extends ConditionWrapper { + + public ConditionAndWrapper() { + andLink = true; + } + + public ConditionAndWrapper and(ConditionWrapper conditionWrapper) { + list.add(conditionWrapper); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionAndWrapper eq(String column, Object params) { + super.eq(column, params); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionAndWrapper eq(SerializableFunction column, Object params) { + super.eq(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper ne(String column, Object params) { + super.ne(column, params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper ne(SerializableFunction column, Object params) { + super.ne(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lt(String column, Object params) { + super.lt(column, params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lt(SerializableFunction column, Object params) { + super.lt(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lte(String column, Object params) { + super.lte(column, params); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper lte(SerializableFunction column, Object params) { + super.lte(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gt(String column, Object params) { + super.gt(column, params); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gt(SerializableFunction column, Object params) { + super.gt(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gte(String column, Object params) { + super.gte(column, params); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper gte(SerializableFunction column, Object params) { + super.gte(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper like(String column, String params) { + super.like(column, params); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper like(SerializableFunction column, String params) { + super.like(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(String column, Collection params) { + super.in(column, params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(SerializableFunction column, Collection params) { + super.in(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(String column, Object[] params) { + super.in(column, Arrays.asList(params)); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper in(SerializableFunction column, Object[] params) { + super.in(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(String column, Collection params) { + super.nin(column, params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(SerializableFunction column, Collection params) { + super.nin(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(String column, Object[] params) { + super.nin(column, Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper nin(SerializableFunction column, Object[] params) { + super.nin(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNull(String column) { + super.isNull(column); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNull(SerializableFunction column) { + super.isNull(ReflectionUtil.getFieldName(column)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNotNull(String column) { + super.isNotNull(column); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionAndWrapper + */ + public ConditionAndWrapper isNotNull(SerializableFunction column) { + super.isNotNull(ReflectionUtil.getFieldName(column)); + return this; + } +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionOrWrapper.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionOrWrapper.java new file mode 100644 index 0000000..fd888a8 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionOrWrapper.java @@ -0,0 +1,321 @@ +package com.cym.sqlHelper.utils; + +import java.util.Arrays; +import java.util.Collection; + +import com.cym.sqlHelper.reflection.ReflectionUtil; +import com.cym.sqlHelper.reflection.SerializableFunction; + +/** + * 查询语句生成器 OR连接 + * + */ +public class ConditionOrWrapper extends ConditionWrapper { + + public ConditionOrWrapper() { + andLink = false; + } + + public ConditionOrWrapper or(ConditionWrapper conditionWrapper) { + list.add(conditionWrapper); + return this; + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionOrWrapper eq(String column, Object params) { + super.eq(column, params); + return this; + } + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionOrWrapper eq(SerializableFunction column, Object params) { + super.eq(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper ne(String column, Object params) { + super.ne(column, params); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper ne(SerializableFunction column, Object params) { + super.ne(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lt(String column, Object params) { + super.lt(column, params); + return this; + } + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lt(SerializableFunction column, Object params) { + super.lt(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lte(String column, Object params) { + super.lte(column, params); + return this; + } + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper lte(SerializableFunction column, Object params) { + super.lte(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gt(String column, Object params) { + super.gt(column, params); + return this; + } + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gt(SerializableFunction column, Object params) { + super.gt(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gte(String column, Object params) { + super.gte(column, params); + return this; + } + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper gte(SerializableFunction column, Object params) { + super.gte(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper like(String column, String params) { + super.like(column, params); + return this; + } + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper like(SerializableFunction column, String params) { + super.like(ReflectionUtil.getFieldName(column), params); + return this; + } + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(String column, Collection params) { + super.in(column, params); + return this; + } + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(SerializableFunction column, Collection params) { + super.in(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(String column, Object[] params) { + super.in(column, Arrays.asList(params)); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper in(SerializableFunction column, Object[] params) { + super.in(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(String column, Collection params) { + super.nin(column, params); + return this; + } + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(SerializableFunction column, Collection params) { + super.nin(ReflectionUtil.getFieldName(column), params); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(String column, Object[] params) { + super.nin(column, Arrays.asList(params)); + return this; + } + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper nin(SerializableFunction column, Object[] params) { + super.nin(ReflectionUtil.getFieldName(column), Arrays.asList(params)); + return this; + } + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNull(String column) { + super.isNull(column); + return this; + } + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNull(SerializableFunction column) { + super.isNull(ReflectionUtil.getFieldName(column)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNotNull(String column) { + super.isNotNull(column); + return this; + } + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionOrWrapper + */ + public ConditionOrWrapper isNotNull(SerializableFunction column) { + super.isNotNull(ReflectionUtil.getFieldName(column)); + return this; + } +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionWrapper.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionWrapper.java new file mode 100644 index 0000000..64a01e1 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/ConditionWrapper.java @@ -0,0 +1,235 @@ +package com.cym.sqlHelper.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import cn.hutool.core.util.StrUtil; + +/** + * 查询语句生成器 + * + * @author CYM + * + */ +public abstract class ConditionWrapper { + boolean andLink; + + List list = new ArrayList(); + + /** + * 将Wrapper转化为Condition + * + * @param params + * + * @return Condition + */ + public String build(List values) { + String sql = ""; + if (list.size() > 0) { + List blocks = new ArrayList(); + for (Object object : list) { + if (object instanceof Condition) { + Condition condition = (Condition) object; + String block = null; + + if (condition.getValue() == null) { + if (condition.getOperation().equals("IS NULL") || condition.getOperation().equals("IS NOT NULL")) { + block = buildColumn(condition.getColumn(), String.class) + " " + condition.getOperation(); + } else { + block = buildColumn(condition.getColumn(), String.class) + " " + condition.getOperation() + " null"; + } + } else { + if (condition.getValue() instanceof List) { + block = buildColumn(condition.getColumn(), condition.getValue().getClass()) + " " + condition.getOperation() + " " + buildIn(condition.getValue()); + for (Object val : (List) condition.getValue()) { + values.add(val); + } + } else { + block = buildColumn(condition.getColumn(), condition.getValue().getClass()) + " " + condition.getOperation() + " ?"; + if (!condition.getOperation().equals("LIKE")) { + values.add(condition.getValue()); + } else { + values.add("%" + condition.getValue().toString().replace("%", "\\%") + "%"); + } + } + } + + blocks.add(block); + } + + if (object instanceof ConditionWrapper) { + ConditionWrapper conditionWrapper = (ConditionWrapper) object; + String block = " (" + conditionWrapper.build(values) + ") "; + blocks.add(block); + } + } + + if (andLink) { + sql = StrUtil.join(" AND ", blocks); + } else { + sql = StrUtil.join(" OR ", blocks); + } + + } + return sql; + } + + public String buildColumn(String column, Class clazz) { + + return "`" + StrUtil.toUnderlineCase(column) + "`"; + } + + public String buildIn(Object value) { + List ask = new ArrayList(); + for (Object obj : (Collection) value) { + ask.add("?"); + } + + if (ask.size() > 0) { + return " (" + StrUtil.join(",", ask) + ") "; + } else { + return " (null) "; + } + + } + + /** + * 等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper eq(String column, Object params) { + list.add(new Condition(column, "=", params)); + return this; + } + + /** + * 不等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper ne(String column, Object params) { + list.add(new Condition(column, "<>", params)); + return this; + } + + /** + * 小于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper lt(String column, Object params) { + list.add(new Condition(column, "<", params)); + return this; + } + + /** + * 小于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper lte(String column, Object params) { + list.add(new Condition(column, "<=", params)); + return this; + } + + /** + * 大于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper gt(String column, Object params) { + list.add(new Condition(column, ">", params)); + return this; + } + + /** + * 大于或等于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper gte(String column, Object params) { + list.add(new Condition(column, ">=", params)); + return this; + } + + /** + * 相似于 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper like(String column, String params) { + list.add(new Condition(column, "LIKE", params )); + return this; + } + + /** + * 在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper in(String column, Collection params) { + list.add(new Condition(column, "IN", params)); + return this; + } + + /** + * 不在其中 + * + * @param column 字段 + * @param params 参数 + * @return ConditionWrapper + */ + public ConditionWrapper nin(String column, Collection params) { + list.add(new Condition(column, "NOT IN", params)); + return this; + } + + /** + * 为空 + * + * @param + * + * @param column 字段 + * @return ConditionWrapper + */ + public ConditionWrapper isNull(String column) { + list.add(new Condition(column, "IS NULL", null)); + return this; + } + + /** + * 不为空 + * + * @param + * + * @param column 字段 + * @return ConditionWrapper + */ + public ConditionWrapper isNotNull(String column) { + list.add(new Condition(column, "IS NOT NULL", null)); + return this; + } + + public boolean notEmpty() { + return list.size() > 0; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SnowFlakeUtils.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SnowFlakeUtils.java new file mode 100644 index 0000000..4e30f48 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SnowFlakeUtils.java @@ -0,0 +1,11 @@ +package com.cym.sqlHelper.utils; + +import cn.hutool.core.util.IdUtil; + +public class SnowFlakeUtils { + + public static Long nextId() { + return IdUtil.getSnowflake(0, 0).nextId(); + } + +} \ No newline at end of file diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlHelper.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlHelper.java new file mode 100644 index 0000000..31f4692 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlHelper.java @@ -0,0 +1,944 @@ +package com.cym.sqlHelper.utils; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.cym.sqlHelper.bean.Page; +import com.cym.sqlHelper.bean.Sort; +import com.cym.sqlHelper.bean.Update; +import com.cym.sqlHelper.config.InitValue; +import com.cym.sqlHelper.reflection.ReflectionUtil; +import com.cym.sqlHelper.reflection.SerializableFunction; + +import cn.hutool.core.util.ClassUtil; +import cn.hutool.core.util.ReflectUtil; +import cn.hutool.core.util.StrUtil; +import jakarta.annotation.PostConstruct; + +/** + * mongodb操作器 + * + */ +@Service +public class SqlHelper extends SqlUtils { + @Value("${spring.database.type}") + String database; + @Value("${spring.database.package}") + String packageName; + @Value("${spring.database.print:false}") + Boolean print; + + @Autowired + JdbcTemplate jdbcTemplate; + + Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + TableUtils tableUtils; + + @PostConstruct + private void scan() { + if (StrUtil.isEmpty(packageName)) { + return; + } + + Set> set = ClassUtil.scanPackage(packageName); + for (Class clazz : set) { + tableUtils.initTable(clazz); + } + } + + /** + * 插入或更新 + * + * @param object 对象 + */ + public String insertOrUpdate(Object object) { + + Long time = System.currentTimeMillis(); + String id = (String) ReflectUtil.getFieldValue(object, "id"); +// Object objectOrg = StrUtil.isNotEmpty(id) ? findById(id, object.getClass()) : null; + try { + if (StrUtil.isEmpty(id)) { + // 插入 + // 设置插入时间 + if (ReflectUtil.getField(object.getClass(), "createTime") != null) { + ReflectUtil.setFieldValue(object, "createTime", time); + } + if (ReflectUtil.getField(object.getClass(), "updateTime") != null) { + ReflectUtil.setFieldValue(object, "updateTime", time); + } + // 设置默认值 + setDefaultVaule(object); + + // 没有id设置id + if (StrUtil.isEmpty(id)) { + ReflectUtil.setFieldValue(object, "id", SnowFlakeUtils.nextId()); + } + + String sql = ""; + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + List paramValues = new ArrayList(); + + Field[] fields = ReflectUtil.getFields(object.getClass()); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + + sql = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + + logQuery(formatSql(sql), paramValues.toArray()); + jdbcTemplate.update(formatSql(sql), paramValues.toArray()); + + } else { + // 更新 + Field[] fields = ReflectUtil.getFields(object.getClass()); + + // 设置更新时间 + if (ReflectUtil.getField(object.getClass(), "updateTime") != null) { + ReflectUtil.setFieldValue(object, "updateTime", time); + } + + List fieldsPart = new ArrayList(); + List paramValues = new ArrayList(); + + for (Field field : fields) { + if (!field.getName().equals("id") && ReflectUtil.getFieldValue(object, field) != null) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`=?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + } + paramValues.add(id); + + String sql = "UPDATE `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart) + " WHERE id = ?"; + + logQuery(formatSql(sql), paramValues.toArray()); + jdbcTemplate.update(formatSql(sql), paramValues.toArray()); + } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + return (String) ReflectUtil.getFieldValue(object, "id"); + } + + /** + * 插入 + * + * @param object 对象 + */ + public String insert(Object object) { +// String id = (String) ReflectUtil.getFieldValue(object, "id"); +// Object objectOrg = StrUtil.isNotEmpty(id) ? findById(id, object.getClass()) : null; +// if (objectOrg != null) { +// // 数据库里已有相同id, 使用新id以便插入 +// ReflectUtil.setFieldValue(object, "id", snowFlake.nextId()); +// } + +// // 没有id生成id +// if (ReflectUtil.getFieldValue(object, "id") == null) { +// ReflectUtil.setFieldValue(object, "id", snowFlake.nextId()); +// } + + // 去除主键id + ReflectUtil.setFieldValue(object, "id", null); + + insertOrUpdate(object); + + return (String) ReflectUtil.getFieldValue(object, "id"); + } + + + /** + * 插入全部字段 + * + * @param object 对象 + */ + public String insertAllColumn(Object object) { + // 没有id生成id + if (ReflectUtil.getFieldValue(object, "id") == null) { + ReflectUtil.setFieldValue(object, "id", SnowFlakeUtils.nextId()); + } + + String sql = ""; + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + List paramValues = new ArrayList(); + + Field[] fields = ReflectUtil.getFields(object.getClass()); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + + sql = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + logQuery(formatSql(sql), paramValues.toArray()); + jdbcTemplate.update(formatSql(sql), paramValues.toArray()); + + // 返回id + return (String) ReflectUtil.getFieldValue(object, "id"); + } + + /** + * 批量插入 + * + * @param + * + * @param object 对象 + */ + public void insertBatch(List list) { + Long time = System.currentTimeMillis(); + +// Map idMap = new HashMap(); +// for (Object object : list) { +// if (ReflectUtil.getFieldValue(object, "id") != null) { +// String id = (String) ReflectUtil.getFieldValue(object, "id"); +// Object objectOrg = StrUtil.isNotEmpty(id) ? findById(id, object.getClass()) : null; +// idMap.put((String) ReflectUtil.getFieldValue(object, "id"), objectOrg); +// } +// } + + for (Object object : list) { +// if (ReflectUtil.getFieldValue(object, "id") != null && idMap.get((String) ReflectUtil.getFieldValue(object, "id")) != null) { +// // 数据库里已有相同id, 使用新id以便插入 +// ReflectUtil.setFieldValue(object, "id", snowFlake.nextId()); +// } + + // 没有id生成id + if (ReflectUtil.getFieldValue(object, "id") == null) { + ReflectUtil.setFieldValue(object, "id", SnowFlakeUtils.nextId()); + } + + // 设置插入时间 + if (ReflectUtil.getField(object.getClass(), "createTime") != null) { + ReflectUtil.setFieldValue(object, "createTime", time); + } + if (ReflectUtil.getField(object.getClass(), "updateTime") != null) { + ReflectUtil.setFieldValue(object, "updateTime", time); + } + // 设置默认值 + setDefaultVaule(object); + } + + List paramValues = new ArrayList(); + String sqls = null; + for (Object object : list) { + Field[] fields = ReflectUtil.getFields(object.getClass()); + + List fieldsPart = new ArrayList(); + List placeHolder = new ArrayList(); + + List params = new ArrayList(); + for (Field field : fields) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`"); + placeHolder.add("?"); + params.add(ReflectUtil.getFieldValue(object, field)); + } + + paramValues.add(params.toArray()); + + if (sqls == null) { + sqls = "INSERT INTO `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` (" + StrUtil.join(",", fieldsPart) + ") VALUES (" + StrUtil.join(",", placeHolder) + ")"; + } + logQuery(formatSql(sqls), params.toArray()); + } + + //logQueryBatch(formatSql(sqls), paramValues); + jdbcTemplate.batchUpdate(formatSql(sqls), paramValues); + } + + /** + * 根据id更新 + * + * @param object 对象 + */ + public void updateById(Object object) { + if (StrUtil.isEmpty((String) ReflectUtil.getFieldValue(object, "id"))) { + return; + } + insertOrUpdate(object); + } + + /** + * 批量更新 + * + * @param conditionAndWrapper + * @param update + * @param clazz + */ + public void updateMulti(ConditionWrapper conditionWrapper, Update update, Class clazz) { + if (update == null || update.getSets().size() == 0) { + return; + } + List fieldsPart = new ArrayList(); + List paramValues = new ArrayList(); + for (Entry entry : update.getSets().entrySet()) { + if (entry.getKey() != null && entry.getValue() != null) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(entry.getKey()) + "`=?"); + paramValues.add(entry.getValue().toString()); + } + } + + String sql = "UPDATE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart); + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(paramValues); + } + + logQuery(formatSql(sql), paramValues.toArray()); + jdbcTemplate.update(formatSql(sql), paramValues.toArray()); + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + public void addCountById(String id, String property, Long count, Class clazz) { + String sql = "UPDATE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` SET `" + property + "` = CAST(`" + property + "` AS DECIMAL(30,10)) + ? WHERE `id` = ?"; + Object[] params = new Object[] { count, id }; + logQuery(formatSql(sql), params); + jdbcTemplate.update(formatSql(sql), params); + } + + /** + * 累加某一个字段的数量,原子操作 + * + * @param object + */ + public void addCountById(String id, SerializableFunction property, Long count, Class clazz) { + addCountById(id, ReflectionUtil.getFieldName(property), count, clazz); + } + + /** + * 根据id更新 + * + * @param object 对象 + */ + public void updateAllColumnById(Object object) { + if (StrUtil.isEmpty((String) ReflectUtil.getFieldValue(object, "id"))) { + return; + } + + Field[] fields = ReflectUtil.getFields(object.getClass()); + + List fieldsPart = new ArrayList(); + List paramValues = new ArrayList(); + + for (Field field : fields) { + if (!field.getName().equals("id")) { + fieldsPart.add("`" + StrUtil.toUnderlineCase(field.getName()) + "`=?"); + paramValues.add(ReflectUtil.getFieldValue(object, field)); + } + } + paramValues.add((String) ReflectUtil.getFieldValue(object, "id")); + + String sql = "UPDATE `" + StrUtil.toUnderlineCase(object.getClass().getSimpleName()) + "` SET " + StrUtil.join(",", fieldsPart) + " WHERE id = ?"; + + logQuery(formatSql(sql), paramValues.toArray()); + jdbcTemplate.update(formatSql(sql), paramValues.toArray()); + + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + public void deleteById(String id, Class clazz) { + + if (StrUtil.isEmpty(id)) { + return; + } + deleteByQuery(new ConditionAndWrapper().eq("id", id), clazz); + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + public void deleteByIds(Collection ids, Class clazz) { + if (ids == null || ids.size() == 0) { + return; + } + + deleteByQuery(new ConditionAndWrapper().in("id", ids), clazz); + } + + /** + * 根据id删除 + * + * @param id 对象 + * @param clazz 类 + */ + public void deleteByIds(String[] ids, Class clazz) { + deleteByIds(Arrays.asList(ids), clazz); + } + + /** + * 根据条件删除 + * + * @param query 查询 + * @param clazz 类 + */ + public void deleteByQuery(ConditionWrapper conditionWrapper, Class clazz) { + List values = new ArrayList(); + String sql = "DELETE FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + logQuery(formatSql(sql), values.toArray()); + jdbcTemplate.update(formatSql(sql), values.toArray()); + } + + /** + * 设置默认值 + * + * @param object 对象 + */ + private void setDefaultVaule(Object object) { + Field[] fields = ReflectUtil.getFields(object.getClass()); + for (Field field : fields) { + // 获取注解 + if (field.isAnnotationPresent(InitValue.class)) { + InitValue defaultValue = field.getAnnotation(InitValue.class); + + String value = defaultValue.value(); + + if (ReflectUtil.getFieldValue(object, field) == null) { + // 获取字段类型 + Class type = field.getType(); + if (type.equals(String.class)) { + ReflectUtil.setFieldValue(object, field, value); + } + if (type.equals(Short.class)) { + ReflectUtil.setFieldValue(object, field, Short.parseShort(value)); + } + if (type.equals(Integer.class)) { + ReflectUtil.setFieldValue(object, field, Integer.parseInt(value)); + } + if (type.equals(Long.class)) { + ReflectUtil.setFieldValue(object, field, Long.parseLong(value)); + } + if (type.equals(Float.class)) { + ReflectUtil.setFieldValue(object, field, Float.parseFloat(value)); + } + if (type.equals(Double.class)) { + ReflectUtil.setFieldValue(object, field, Double.parseDouble(value)); + } + if (type.equals(Boolean.class)) { + ReflectUtil.setFieldValue(object, field, Boolean.parseBoolean(value)); + } + } + } + } + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPage(ConditionWrapper conditionWrapper, Sort sort, Page page, Class clazz) { + List values = new ArrayList(); + // 查询出一共的条数 + Long count = findCountByQuery(conditionWrapper, clazz); + + String sql = "SELECT * FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + if (sort != null) { + sql += " " + sort.toString(); + } else { + sql += " ORDER BY id DESC"; + } + if (database.equalsIgnoreCase("mysql") || database.equalsIgnoreCase("sqlite")) { + sql += " LIMIT " + (page.getCurr() - 1) * page.getLimit() + "," + page.getLimit(); + } else { + sql += " LIMIT " + page.getLimit() + " OFFSET " + (page.getCurr() - 1) * page.getLimit(); + } + + page.setCount(count); + + logQuery(formatSql(sql), values.toArray()); + page.setRecords(buildObjects(jdbcTemplate.queryForList(formatSql(sql), values.toArray()), clazz)); + + return page; + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPage(Sort sort, Page page, Class clazz) { + return findPage(null, sort, page, clazz); + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPage(ConditionWrapper conditionWrapper, Page page, Class clazz) { + return findPage(conditionWrapper, null, page, clazz); + } + + /** + * 按查询条件获取Page + * + * @param query 查询 + * @param page 分页 + * @param clazz 类 + * @return Page 分页 + */ + public Page findPage(Page page, Class clazz) { + return findPage(null, null, page, clazz); + } + + /** + * 根据id查找 + * + * @param id id + * @param clazz 类 + * @return T 对象 + */ + public T findById(String id, Class clazz) { + if (StrUtil.isEmpty(id)) { + return null; + } + + return findOneByQuery(new ConditionAndWrapper().eq("id", id), clazz); + + } + + /** + * 根据条件查找单个 + * + * @param query 查询 + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(ConditionWrapper conditionWrapper, Sort sort, Class clazz) { + List values = new ArrayList(); + List list = new ArrayList(); + String sql = "SELECT * FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + if (sort != null) { + sql += " " + sort.toString(); + } else { + sql += " ORDER BY id DESC"; + } + sql += " limit 1"; + + logQuery(formatSql(sql), values.toArray()); + list = buildObjects(jdbcTemplate.queryForList(formatSql(sql), values.toArray()), clazz); + return list.size() > 0 ? list.get(0) : null; + } + + /** + * 根据条件查找单个 + * + * @param query 查询 + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(Sort sort, Class clazz) { + return findOneByQuery(null, sort, clazz); + } + + /** + * 根据条件查找单个 + * + * @param 类型 + * @param condition + * @param clazz 类 + * @return T 对象 + */ + public T findOneByQuery(ConditionWrapper conditionWrapper, Class clazz) { + return findOneByQuery(conditionWrapper, null, clazz); + + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param query 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(ConditionWrapper conditionWrapper, Sort sort, Class clazz) { + List values = new ArrayList(); + + String sql = "SELECT * FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + if (sort != null) { + sql += " " + sort.toString(); + } else { + sql += " ORDER BY id DESC"; + } + + logQuery(formatSql(sql), values.toArray()); + return buildObjects(jdbcTemplate.queryForList(formatSql(sql), values.toArray()), clazz); + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(ConditionWrapper conditionWrapper, Class clazz) { + return (List) findListByQuery(conditionWrapper, null, clazz); + } + + /** + * 根据条件查找List + * + * @param 类型 + * @param condition 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findListByQuery(Sort sort, Class clazz) { + return (List) findListByQuery(null, sort, clazz); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param query 查询 + * @param documentClass 类 + * @param property 属性 + * @param propertyClass 属性类 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class documentClass, String property, Class propertyClass) { + List list = findListByQuery(conditionWrapper, documentClass); + List propertyList = extractProperty(list, property, propertyClass); + + return propertyList; + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param query 查询 + * @param documentClass 类 + * @param property 属性 + * @param propertyClass 属性类 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class documentClass, SerializableFunction property, Class propertyClass) { + return findPropertiesByQuery(conditionWrapper, documentClass, ReflectionUtil.getFieldName(property), propertyClass); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class documentClass, String property) { + return findPropertiesByQuery(conditionWrapper, documentClass, property, String.class); + } + + /** + * 根据条件查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByQuery(ConditionWrapper conditionWrapper, Class documentClass, SerializableFunction property) { + return findPropertiesByQuery(conditionWrapper, documentClass, ReflectionUtil.getFieldName(property), String.class); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(Collection ids, Class documentClass, String property) { + if (ids == null || ids.size() == 0) { + return new ArrayList(); + } + + ConditionAndWrapper ConditionAndWrapper = new ConditionAndWrapper(); + ConditionAndWrapper.in("id", ids); + + return findPropertiesByQuery(ConditionAndWrapper, documentClass, property, String.class); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(Collection ids, Class documentClass, SerializableFunction property) { + return findPropertiesByIds(ids, documentClass, ReflectionUtil.getFieldName(property)); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(String[] ids, Class documentClass, String property) { + return findPropertiesByIds(Arrays.asList(ids), documentClass, property); + } + + /** + * 根据id查找某个属性 + * + * @param 类型 + * @param condition 查询 + * @param documentClass 类 + * @param property 属性 + * @return List 列表 + */ + public List findPropertiesByIds(String[] ids, Class documentClass, SerializableFunction property) { + return findPropertiesByIds(Arrays.asList(ids), documentClass, ReflectionUtil.getFieldName(property)); + } + + /** + * 根据条件查找id + * + * @param query 查询 + * @param clazz 类 + * @return List 列表 + */ + public List findIdsByQuery(ConditionWrapper conditionWrapper, Class clazz) { + + return findPropertiesByQuery(conditionWrapper, clazz, "id"); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(Collection ids, Class clazz) { + return findListByIds(ids, null, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(String[] ids, Class clazz) { + return findListByIds(Arrays.asList(ids), null, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(Collection ids, Sort sort, Class clazz) { + if (ids == null || ids.size() == 0) { + return new ArrayList(); + } + + ConditionAndWrapper ConditionAndWrapper = new ConditionAndWrapper(); + ConditionAndWrapper.in("id", ids); + + return findListByQuery(ConditionAndWrapper, sort, clazz); + } + + /** + * 根据id集合查找 + * + * @param List ids id集合 + * @param clazz 类 + * @return List 列表 + */ + public List findListByIds(String[] ids, Sort sort, Class clazz) { + return findListByIds(Arrays.asList(ids), sort, clazz); + } + + /** + * 查询全部 + * + * @param 类型 + * @param clazz 类 + * @return List 列表 + */ + public List findAll(Class clazz) { + return findAll(null, clazz); + } + + /** + * 查询全部 + * + * @param 类型 + * @param clazz 类 + * @return List 列表 + */ + public List findAll(Sort sort, Class clazz) { + return findListByQuery(null, sort, clazz); + } + + /** + * 查找全部的id + * + * @param clazz 类 + * @return List 列表 + */ + public List findAllIds(Class clazz) { + return findIdsByQuery(null, clazz); + } + + /** + * 查找数量 + * + * @param condition 查询 + * @param clazz 类 + * @return Long 数量 + */ + public Long findCountByQuery(ConditionWrapper conditionWrapper, Class clazz) { + List values = new ArrayList(); + String sql = "SELECT COUNT(*) FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + if (conditionWrapper != null && conditionWrapper.notEmpty()) { + sql += " WHERE " + conditionWrapper.build(values); + } + + logQuery(formatSql(sql), values.toArray()); + return jdbcTemplate.queryForObject(formatSql(sql), values.toArray(), Long.class); + } + + /** + * 查找全部数量 + * + * @param clazz 类 + * @return Long 数量 + */ + public Long findAllCount(Class clazz) { + return findCountByQuery(null, clazz); + } + + /** + * 获取list中对象某个属性,组成新的list + * + * @param list 列表 + * @param clazz 类 + * @param property 属性 + * @return List 列表 + */ + private List extractProperty(List list, String property, Class clazz) { + Set rs = new HashSet(); + for (Object object : list) { + Object value = ReflectUtil.getFieldValue(object, property); + if (value != null && value.getClass().equals(clazz)) { + rs.add((T) value); + } + } + + return new ArrayList(rs); + } + + /** + * Map转Bean + * + * @param + * @param queryForList + * @param clazz + * @return + */ + private List buildObjects(List> queryForList, Class clazz) { + List list = new ArrayList(); + try { + + Field[] fields = ReflectUtil.getFields(clazz); + + for (Map map : queryForList) { + Object obj = clazz.getDeclaredConstructor().newInstance(); + + for (Map.Entry entry : map.entrySet()) { + String mapKey = entry.getKey(); + Object mapValue = entry.getValue(); + + for (Field field : fields) { + if (StrUtil.toUnderlineCase(field.getName()).equals(mapKey)) { + ReflectUtil.setFieldValue(obj, field.getName(), mapValue); + break; + } + } + + } + + list.add((T) obj); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return list; + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlUtils.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlUtils.java new file mode 100644 index 0000000..cd719e1 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/SqlUtils.java @@ -0,0 +1,151 @@ +package com.cym.sqlHelper.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import cn.hutool.core.util.StrUtil; + +@Component +public class SqlUtils { + Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Value("${spring.database.type}") + String database; + @Value("${spring.database.package}") + String packageName; + @Value("${spring.database.print:false}") + Boolean print; + @Autowired + JdbcTemplate jdbcTemplate; + + String separator = System.getProperty("line.separator"); + + + public String formatSql(String sql) { + if (StrUtil.isEmpty(sql)) { + return ""; + } + + if (!database.equalsIgnoreCase("mysql")) { + sql = sql.replace("`", "\""); + } + + sql = sql.replace("FROM", separator + "FROM")// + .replace("WHERE", separator + "WHERE")// + .replace("ORDER", separator + "ORDER")// + .replace("LIMIT", separator + "LIMIT")// + .replace("VALUES", separator + "VALUES");// + return sql; + } + + public void checkOrCreateTable(Class clazz) { + String sql = "CREATE TABLE IF NOT EXISTS `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` (id VARCHAR(32) NOT NULL PRIMARY KEY)"; + logQuery(formatSql(sql)); + jdbcTemplate.execute(formatSql(sql)); + + } + + public void logQuery(String sql) { + logQuery(sql, null); + } + + public void logQuery(String sql, Object[] params) { + if (print) { + try { + if (params != null) { + for (Object object : params) { + + if (object instanceof String) { + object = object.toString().replace("$", "RDS_CHAR_DOLLAR"); + sql = sql.replaceFirst("\\?", "'" + object + "'").replace("RDS_CHAR_DOLLAR", "$"); + } else { + sql = sql.replaceFirst("\\?", String.valueOf(object)); + } + + } + } + logger.info(separator + sql); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + + + + public void checkOrCreateIndex(Class clazz, String name, boolean unique, List> indexs) { + checkOrCreateIndex(clazz, new String[] { name }, unique, indexs); + } + + public void checkOrCreateIndex(Class clazz, String[] colums, boolean unique, List> indexs) { + List columList = new ArrayList(); + for (String colum : colums) { + columList.add(StrUtil.toUnderlineCase(colum)); + } + String name = StrUtil.join("&", columList) + "@" + StrUtil.toUnderlineCase(clazz.getSimpleName()); + + Boolean hasIndex = false; + for (Map map : indexs) { + if (StrUtil.toUnderlineCase(name).equalsIgnoreCase((String) map.get("name")) || StrUtil.toUnderlineCase(name).equalsIgnoreCase((String) map.get("Key_name"))) { + hasIndex = true; + } + } + + if (!hasIndex) { + String type = unique ? "UNIQUE INDEX" : "INDEX"; + String length = ""; + if (database.equals("mysql")) { + length = "(128)"; + } + + columList = new ArrayList(); + for (String colum : colums) { + columList.add(StrUtil.toUnderlineCase("`" + colum + "`" + length)); + } + + String sql = "CREATE " + type + " `" + StrUtil.toUnderlineCase(name) + "` ON `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`(" + StrUtil.join(",", columList) + ")"; + logQuery(formatSql(sql)); + jdbcTemplate.execute(formatSql(sql)); + } + + } + + public void checkOrCreateColumn(Class clazz, String name, List> columns) { + Boolean hasColumn = false; + for (Map map : columns) { + if (StrUtil.toUnderlineCase(name).equalsIgnoreCase((String) map.get("name")) || StrUtil.toUnderlineCase(name).equalsIgnoreCase((String) map.get("Field"))) { + hasColumn = true; + } + } + + if (!hasColumn) { + String sql = "ALTER TABLE `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "` ADD COLUMN `" + StrUtil.toUnderlineCase(name) + "` TEXT"; + logQuery(formatSql(sql)); + jdbcTemplate.execute(formatSql(sql)); + } + + } + + + public void updateDefaultValue(Class clazz, String column, String value) { + String sql = "SELECT COUNT(*) FROM " + StrUtil.toUnderlineCase(clazz.getSimpleName()) + " WHERE `" + StrUtil.toUnderlineCase(column) + "` IS NULL"; + logQuery(formatSql(sql)); + Long count = jdbcTemplate.queryForObject(formatSql(sql), Long.class); + if (count > 0) { + sql = "UPDATE " + StrUtil.toUnderlineCase(clazz.getSimpleName()) + " SET `" + StrUtil.toUnderlineCase(column) + "` = ? WHERE `" + StrUtil.toUnderlineCase(column) + "` IS NULL"; + logQuery(formatSql(sql)); + jdbcTemplate.update(formatSql(sql), value); + } + + } + +} diff --git a/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/TableUtils.java b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/TableUtils.java new file mode 100644 index 0000000..7471172 --- /dev/null +++ b/lib/sqlHelper/src/main/java/com/cym/sqlHelper/utils/TableUtils.java @@ -0,0 +1,107 @@ +package com.cym.sqlHelper.utils; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import com.cym.sqlHelper.config.CompositeIndex; +import com.cym.sqlHelper.config.InitValue; +import com.cym.sqlHelper.config.SingleIndex; +import com.cym.sqlHelper.config.Table; + +import cn.hutool.core.util.ReflectUtil; +import cn.hutool.core.util.StrUtil; + +@Component +public class TableUtils { + Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Value("${spring.database.type}") + String database; + @Value("${spring.database.package}") + String packageName; + @Autowired + JdbcTemplate jdbcTemplate; + @Autowired + SqlUtils sqlUtils; + + + public void initTable(Class clazz) { + Table table = clazz.getAnnotation(Table.class); + if (table != null) { + // 创建表 + sqlUtils.checkOrCreateTable(clazz); + + // 获取表所有字段 + String sql = ""; + if (database.equals("sqlite")) { + sql = "PRAGMA TABLE_INFO(`" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`)"; + } else if (database.equals("mysql")) { + sql = "SHOW COLUMNS FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + } else if (database.equals("postgresql")) { + sql = "SELECT column_name as name FROM information_schema.columns " + // + "WHERE table_schema='public' AND table_name='" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "'"; + } + sqlUtils.logQuery(sqlUtils.formatSql(sql)); + List> columns = jdbcTemplate.queryForList(sqlUtils.formatSql(sql)); + + // 获取表所有索引 + if (database.equals("sqlite")) { + sql = "PRAGMA INDEX_LIST(`" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`)"; + } else if (database.equals("mysql")) { + sql = "SHOW INDEX FROM `" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "`"; + } else if (database.equals("postgresql")) { + sql = "SELECT " + // + "A.INDEXNAME as name " + // + "FROM PG_AM B " + // + "LEFT JOIN PG_CLASS F ON B.OID = F.RELAM " + // + "LEFT JOIN PG_STAT_ALL_INDEXES E ON F.OID = E.INDEXRELID " + // + "LEFT JOIN PG_INDEX C ON E.INDEXRELID = C.INDEXRELID " + // + "LEFT OUTER JOIN PG_DESCRIPTION D ON C.INDEXRELID = D.OBJOID, " + // + "PG_INDEXES A " + // + "WHERE " + // + "A.SCHEMANAME = E.SCHEMANAME AND A.TABLENAME = E.RELNAME AND A.INDEXNAME = E.INDEXRELNAME " + // + "AND E.SCHEMANAME = 'public' AND E.RELNAME = '" + StrUtil.toUnderlineCase(clazz.getSimpleName()) + "' ";// + } + sqlUtils.logQuery(sqlUtils.formatSql(sql)); + List> indexs = jdbcTemplate.queryForList(sqlUtils.formatSql(sql)); + + // 建立字段 + Field[] fields = ReflectUtil.getFields(clazz); + for (Field field : fields) { + // 创建字段 + if (!field.getName().equals("id")) { + sqlUtils.checkOrCreateColumn(clazz, field.getName(), columns); + } + + // 创建索引 + if (field.isAnnotationPresent(SingleIndex.class)) { + SingleIndex singleIndex = field.getAnnotation(SingleIndex.class); + sqlUtils.checkOrCreateIndex(clazz, field.getName(), singleIndex.unique(), indexs); + } + + // 更新表默认值 + if (field.isAnnotationPresent(InitValue.class)) { + InitValue defaultValue = field.getAnnotation(InitValue.class); + if (defaultValue.value() != null) { + sqlUtils.updateDefaultValue(clazz, field.getName(), defaultValue.value()); + } + } + } + + // 获取组合索引 + if (clazz.isAnnotationPresent(CompositeIndex.class)) { + CompositeIndex compositeIndex = clazz.getAnnotation(CompositeIndex.class); + sqlUtils.checkOrCreateIndex(clazz, compositeIndex.colums(), compositeIndex.unique(), indexs); + } + } + } + +} diff --git a/lib/sqlHelper/src/test/java/cn/craccd/test/Test.java b/lib/sqlHelper/src/test/java/cn/craccd/test/Test.java new file mode 100644 index 0000000..2675041 --- /dev/null +++ b/lib/sqlHelper/src/test/java/cn/craccd/test/Test.java @@ -0,0 +1 @@ +package cn.craccd.test; \ No newline at end of file