Commit b23101e3 authored by yanzg's avatar yanzg

Merge remote-tracking branch 'origin/master'

parents bed37658 2a6fb6bd
//package com.yanzuoguang.util;
//
//import com.yanzuoguang.util.base.MethodField;
//import com.yanzuoguang.util.base.ObjectHelper;
//import com.yanzuoguang.util.helper.JsonHelper;
//import com.yanzuoguang.util.helper.StringHelper;
//import com.yanzuoguang.util.vo.BaseVo;
//import com.yanzuoguang.util.vo.InitDao;
//
//import java.util.HashMap;
//
///**
// * 座次图关联表
// *
// * @author 朱磊
// */
//public class SetSetpictureVo extends BaseVo implements InitDao {
//
// /**
// * 座次图关联ID
// */
// private String setPictureId = "setPictureId";
// /**
// * 座次图ID
// */
// private String pictureId = "pictureId";
//
// @Override
// public void init() {
// this.setPictureId = StringHelper.getFirst(this.setPictureId, StringHelper.EMPTY);
// this.pictureId = StringHelper.getFirst(this.pictureId, StringHelper.EMPTY);
// }
//
// public String getSetPictureId() {
// return setPictureId;
// }
//
// public void setSetPictureId(String setPictureId) {
// this.setPictureId = setPictureId;
// }
//
// public String getPictureId() {
// return pictureId;
// }
//
// public void setPictureId(String pictureId) {
// this.pictureId = pictureId;
// }
//
// public static void main(String[] args) {
// SetSetpictureVo set = new SetSetpictureVo();
// System.out.println(ObjectHelper.get(set, "setPictureId"));
// System.out.println(ObjectHelper.get(set, "pictureId"));
//
// HashMap<String, MethodField> initTypeField = ObjectHelper.getTypeField(SetSetpictureVo.class);
// System.out.println(JsonHelper.serialize(initTypeField));
// }
//}
...@@ -12,21 +12,62 @@ public class MethodField { ...@@ -12,21 +12,62 @@ public class MethodField {
/** /**
* 名称 * 名称
*/ */
public String name; private String name;
/** /**
* 缩写名称 * 缩写名称
*/ */
public String nameSimple; private String nameSimple;
/** /**
* 对应的字段 * 对应的字段
*/ */
public Field field; private Field field;
/** /**
* 对应的获取方法 * 对应的获取方法
*/ */
public Method getMethod; private Method getMethod;
/** /**
* 对应的设置方法 * 对应的设置方法
*/ */
public Method setMethod; private Method setMethod;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameSimple() {
return nameSimple;
}
public void setNameSimple(String nameSimple) {
this.nameSimple = nameSimple;
}
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public Method getGetMethod() {
return getMethod;
}
public void setGetMethod(Method getMethod) {
this.getMethod = getMethod;
}
public Method getSetMethod() {
return setMethod;
}
public void setSetMethod(Method setMethod) {
this.setMethod = setMethod;
}
} }
...@@ -5,10 +5,7 @@ import com.yanzuoguang.util.exception.CodeException; ...@@ -5,10 +5,7 @@ import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import java.lang.reflect.Array; import java.lang.reflect.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
/** /**
...@@ -156,10 +153,10 @@ public class ObjectHelper { ...@@ -156,10 +153,10 @@ public class ObjectHelper {
return null; return null;
} }
try { try {
if (item.field != null && Modifier.isPublic(item.field.getModifiers())) { if (item.getField() != null && Modifier.isPublic(item.getField().getModifiers())) {
return item.field.get(target); return item.getField().get(target);
} else if (item.getMethod != null && Modifier.isPublic(item.getMethod.getModifiers())) { } else if (item.getGetMethod() != null && Modifier.isPublic(item.getGetMethod().getModifiers())) {
return item.getMethod.invoke(target); return item.getGetMethod().invoke(target);
} }
} catch (Exception ex) { } catch (Exception ex) {
ExceptionHelper.handleException(ObjectHelper.class, ex, field); ExceptionHelper.handleException(ObjectHelper.class, ex, field);
...@@ -206,17 +203,21 @@ public class ObjectHelper { ...@@ -206,17 +203,21 @@ public class ObjectHelper {
return; return;
} }
try { try {
if (item.field != null && Modifier.isPublic(item.field.getModifiers())) { setByType(target, item, value);
Class toType = item.field.getType();
Object toValue = StringHelper.to(toType, value);
item.field.set(target, toValue);
} else if (item.setMethod != null && Modifier.isPublic(item.setMethod.getModifiers())) {
Class toType = item.setMethod.getParameterTypes()[0];
Object toValue = StringHelper.to(toType, value);
item.setMethod.invoke(target, toValue);
}
} catch (Exception ex) { } catch (Exception ex) {
ExceptionHelper.handleException(ObjectHelper.class, ex, field); ExceptionHelper.handleException(ObjectHelper.class, ex, item.getName());
}
}
public static void setByType(Object target, MethodField item, Object value) throws IllegalAccessException, InvocationTargetException {
if (item.getField() != null && Modifier.isPublic(item.getField().getModifiers())) {
Class toType = item.getField().getType();
Object toValue = StringHelper.to(toType, value);
item.getField().set(target, toValue);
} else if (item.getSetMethod() != null && Modifier.isPublic(item.getSetMethod().getModifiers())) {
Class toType = item.getSetMethod().getParameterTypes()[0];
Object toValue = StringHelper.to(toType, value);
item.getSetMethod().invoke(target, toValue);
} }
} }
...@@ -247,15 +248,15 @@ public class ObjectHelper { ...@@ -247,15 +248,15 @@ public class ObjectHelper {
* 获取缓存中的字段 * 获取缓存中的字段
* @param typeCache 类型 * @param typeCache 类型
* @param fromName 来源名称 * @param fromName 来源名称
* @param toName 目标名称
* @return * @return
*/ */
private static MethodField getField(HashMap<String, MethodField> typeCache, String fromName) { private static MethodField getField(HashMap<String, MethodField> typeCache, String fromName, String toName) {
String toName = getSimpleName(fromName);
if (!typeCache.containsKey(toName)) { if (!typeCache.containsKey(toName)) {
MethodField newObj = new MethodField(); MethodField newObj = new MethodField();
typeCache.put(toName, newObj); typeCache.put(toName, newObj);
newObj.name = fromName; newObj.setName(fromName);
newObj.nameSimple = toName; newObj.setNameSimple(toName);
} }
return typeCache.get(toName); return typeCache.get(toName);
} }
...@@ -267,7 +268,7 @@ public class ObjectHelper { ...@@ -267,7 +268,7 @@ public class ObjectHelper {
* @return * @return
*/ */
private static String getSimpleName(String fromName) { private static String getSimpleName(String fromName) {
String toName = fromName.toLowerCase().replace("_", ""); String toName = getSimpleFieldName(fromName);
if (toName.startsWith(METHOD_IS)) { if (toName.startsWith(METHOD_IS)) {
toName = toName.substring(METHOD_IS.length()); toName = toName.substring(METHOD_IS.length());
} else if (toName.startsWith(METHOD_GET)) { } else if (toName.startsWith(METHOD_GET)) {
...@@ -277,7 +278,18 @@ public class ObjectHelper { ...@@ -277,7 +278,18 @@ public class ObjectHelper {
} else { } else {
return toName; return toName;
} }
return getSimpleName(toName); return toName;
}
/**
* 获取字段处理名称
*
* @param fromName 字段名称
* @return 属性名称
*/
private static String getSimpleFieldName(String fromName) {
String toName = fromName.toLowerCase().replace("_", "");
return toName;
} }
/** /**
...@@ -303,12 +315,13 @@ public class ObjectHelper { ...@@ -303,12 +315,13 @@ public class ObjectHelper {
// 忽略大小写、忽略下划线 _ // 忽略大小写、忽略下划线 _
for (Field field : fields) { for (Field field : fields) {
MethodField obj = getField(typeCache, field.getName());
if (Modifier.isStatic(field.getModifiers())) { if (Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
if (obj.field == null) { String toName = getSimpleFieldName(field.getName());
obj.field = field; MethodField obj = getField(typeCache, field.getName(), toName);
if (obj.getField() == null) {
obj.setField(field);
} }
} }
for (Method method : methods) { for (Method method : methods) {
...@@ -317,31 +330,32 @@ public class ObjectHelper { ...@@ -317,31 +330,32 @@ public class ObjectHelper {
} }
String methodNameSource = method.getName(); String methodNameSource = method.getName();
String methodNameSimple = methodNameSource.toLowerCase(); String methodNameSimple = methodNameSource.toLowerCase();
String toName = getSimpleName(methodNameSource);
if ("getClass".equals(methodNameSource)) { if ("getClass".equals(methodNameSource)) {
continue; continue;
} else if (methodNameSimple.startsWith("set")) { } else if (methodNameSimple.startsWith("set")) {
if (method.getParameterTypes().length != 1) { if (method.getParameterTypes().length != 1) {
continue; continue;
} }
MethodField obj = getField(typeCache, methodNameSource); MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.setMethod == null) { if (obj.getSetMethod() == null) {
obj.setMethod = method; obj.setSetMethod(method);
} }
} else if (methodNameSimple.startsWith("get")) { } else if (methodNameSimple.startsWith("get")) {
if (method.getReturnType() == null) { if (method.getReturnType() == null) {
continue; continue;
} }
MethodField obj = getField(typeCache, methodNameSource); MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.getMethod == null) { if (obj.getGetMethod() == null) {
obj.getMethod = method; obj.setGetMethod(method);
} }
} else if (methodNameSimple.startsWith("is")) { } else if (methodNameSimple.startsWith("is")) {
if (method.getReturnType() == null) { if (method.getReturnType() == null) {
continue; continue;
} }
MethodField obj = getField(typeCache, methodNameSource); MethodField obj = getField(typeCache, methodNameSource,toName);
if (obj.getMethod == null) { if (obj.getGetMethod() == null) {
obj.getMethod = method; obj.setGetMethod(method);
} }
} }
} }
...@@ -374,7 +388,7 @@ public class ObjectHelper { ...@@ -374,7 +388,7 @@ public class ObjectHelper {
*/ */
private static MethodField getMethodField(Class<?> type, String name) { private static MethodField getMethodField(Class<?> type, String name) {
HashMap<String, MethodField> typeCache = getTypeField(type); HashMap<String, MethodField> typeCache = getTypeField(type);
name = getSimpleName(name); name = getSimpleFieldName(name);
return typeCache.containsKey(name) ? typeCache.get(name) : null; return typeCache.containsKey(name) ? typeCache.get(name) : null;
} }
...@@ -538,7 +552,7 @@ public class ObjectHelper { ...@@ -538,7 +552,7 @@ public class ObjectHelper {
return to; return to;
} }
for (Map.Entry<String, MethodField> field : mapField.entrySet()) { for (Map.Entry<String, MethodField> field : mapField.entrySet()) {
String name = field.getValue().name; String name = field.getValue().getName();
Object fromValue = ObjectHelper.get(from, name); Object fromValue = ObjectHelper.get(from, name);
if (StringHelper.isEmpty(fromValue)) { if (StringHelper.isEmpty(fromValue)) {
continue; continue;
......
...@@ -16,7 +16,7 @@ public class MemoryCacheCenter { ...@@ -16,7 +16,7 @@ public class MemoryCacheCenter {
/** /**
* 缓存的对象 * 缓存的对象
*/ */
public static List<MemoryCache> CLEAR_LIST = new Vector<MemoryCache>(); public final static List<MemoryCache> CLEAR_LIST = new Vector<MemoryCache>();
static { static {
init(); init();
......
...@@ -2,6 +2,7 @@ package com.yanzuoguang.util.exception; ...@@ -2,6 +2,7 @@ package com.yanzuoguang.util.exception;
/** /**
* 途比达异常信息 * 途比达异常信息
*
* @author 颜佐光 * @author 颜佐光
*/ */
public class CodeException extends RuntimeException { public class CodeException extends RuntimeException {
...@@ -57,6 +58,15 @@ public class CodeException extends RuntimeException { ...@@ -57,6 +58,15 @@ public class CodeException extends RuntimeException {
this.code = code; this.code = code;
} }
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
* @param target  错误数据源,如订单数据
*/
public CodeException(String code, String message, Object target) { public CodeException(String code, String message, Object target) {
super(message); super(message);
this.code = code; this.code = code;
......
...@@ -29,6 +29,8 @@ public class ByteHelper { ...@@ -29,6 +29,8 @@ public class ByteHelper {
*/ */
public static final int BCD_MAX_FLAG = 100; public static final int BCD_MAX_FLAG = 100;
private ByteHelper(){}
// --------------------------------------- toLH ------------------------------------- // --------------------------------------- toLH -------------------------------------
/** /**
...@@ -554,6 +556,7 @@ public class ByteHelper { ...@@ -554,6 +556,7 @@ public class ByteHelper {
* @return 转换之后的值 * @return 转换之后的值
*/ */
public static int fromBCD(byte from) { public static int fromBCD(byte from) {
return (from / BYTE_HEX_UNIT) * BYTE_TEN_UNIT + from % BYTE_HEX_UNIT; return (from / BYTE_HEX_UNIT) * BYTE_TEN_UNIT + from %
BYTE_HEX_UNIT;
} }
} }
...@@ -11,12 +11,13 @@ import java.util.regex.Pattern; ...@@ -11,12 +11,13 @@ import java.util.regex.Pattern;
/** /**
* 参数业务逻辑校验 * 参数业务逻辑校验
*
* @author 颜佐光 * @author 颜佐光
*/ */
public final class CheckerHelper { public final class CheckerHelper {
public static final String PARAM_NOT_NULL_TIPS = "param [%s] is null"; public static final String PARAM_NOT_NULL_TIPS = "param [%s] is null";
public static final String PARAM_NOT_EMPTY_TIPS = "param [%s] is empty"; public static final String PARAM_NOT_EMPTY_TIPS = "param [%s] is empty";
public static final String PARAM_NOT_NUMBER = "param [%s] must be number"; public static final String PARAM_NOT_NUMBER = "param [%s] value [%s] must be number";
public static final String PARAM_OVER_MAX_LENGTH = "param [%s] maxlength is "; public static final String PARAM_OVER_MAX_LENGTH = "param [%s] maxlength is ";
public static final String PARAM_NOT_DATE_MONTH = "param [%s] must be yyyyMM"; public static final String PARAM_NOT_DATE_MONTH = "param [%s] must be yyyyMM";
...@@ -176,9 +177,6 @@ public final class CheckerHelper { ...@@ -176,9 +177,6 @@ public final class CheckerHelper {
String eL = ""; String eL = "";
String msg = ""; String msg = "";
if (StringHelper.isEmpty(paramVal)) { if (StringHelper.isEmpty(paramVal)) {
msg = PARAM_NOT_NULL_TIPS;
this.checkResult = String.format(msg, paramName, paramVal);
this.setValid(false);
return this; return this;
} }
if (DATE_CHECK_TYPE_DAY.equals(queryType)) { if (DATE_CHECK_TYPE_DAY.equals(queryType)) {
...@@ -272,7 +270,7 @@ public final class CheckerHelper { ...@@ -272,7 +270,7 @@ public final class CheckerHelper {
SimpleDateFormat format = new SimpleDateFormat(formatStr); SimpleDateFormat format = new SimpleDateFormat(formatStr);
format.parse(paramVal); format.parse(paramVal);
} else { } else {
DateAutoHelper.getAutoDate(formatStr); DateAutoHelper.getAutoDate(paramVal);
} }
} catch (ParseException e) { } catch (ParseException e) {
this.checkResult = String.format(PARAM_NOT_DATE, paramName, formatStr); this.checkResult = String.format(PARAM_NOT_DATE, paramName, formatStr);
...@@ -328,7 +326,7 @@ public final class CheckerHelper { ...@@ -328,7 +326,7 @@ public final class CheckerHelper {
return this; return this;
} }
if (paramVal < min) { if (paramVal < min) {
this.checkResult = String.format(PARAM_NOT_MIN, min, paramName); this.checkResult = String.format(PARAM_NOT_MIN, paramName, min);
this.setValid(false); this.setValid(false);
} }
return this; return this;
...@@ -347,7 +345,7 @@ public final class CheckerHelper { ...@@ -347,7 +345,7 @@ public final class CheckerHelper {
return this; return this;
} }
if (paramVal > max) { if (paramVal > max) {
this.checkResult = String.format(PARAM_NOT_MAX, max, paramName); this.checkResult = String.format(PARAM_NOT_MAX, paramName, max);
this.setValid(false); this.setValid(false);
} }
return this; return this;
...@@ -367,7 +365,7 @@ public final class CheckerHelper { ...@@ -367,7 +365,7 @@ public final class CheckerHelper {
return this; return this;
} }
if (paramVal > max || paramVal < min) { if (paramVal > max || paramVal < min) {
this.checkResult = String.format(PARAM_NOT_RANGE, min, max, paramName); this.checkResult = String.format(PARAM_NOT_RANGE, paramName, min, max);
this.setValid(false); this.setValid(false);
} }
return this; return this;
......
...@@ -87,18 +87,24 @@ public class FileHelper { ...@@ -87,18 +87,24 @@ public class FileHelper {
try { try {
// 删除文件 // 删除文件
if (file.exists()) { if (file.exists()) {
file.delete(); if (!file.delete()) {
throw new CodeException("文件删除失败");
}
} }
if (file.exists()) { if (file.exists()) {
throw new CodeException("文件删除失败"); throw new CodeException("文件删除失败");
} }
// 创建文件夹 // 创建文件夹
File parentFile = file.getParentFile(); File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) { if (parentFile != null) {
parentFile.mkdirs(); if (!parentFile.exists()) {
} if (!parentFile.mkdirs()) {
if (!parentFile.exists()) { throw new CodeException("创建文件夹失败");
throw new CodeException("创建文件夹失败"); }
}
if (!parentFile.exists()) {
throw new CodeException("创建文件夹失败");
}
} }
file.createNewFile(); file.createNewFile();
// 写入文件 // 写入文件
......
...@@ -86,7 +86,7 @@ public class HttpHelper { ...@@ -86,7 +86,7 @@ public class HttpHelper {
*/ */
public static String post(HttpURLConnection httpConn, String jsonString) throws IOException { public static String post(HttpURLConnection httpConn, String jsonString) throws IOException {
// 返回的结果 // 返回的结果
String result = ""; StringBuilder result = new StringBuilder();
// 读取响应输入流 // 读取响应输入流
BufferedReader in = null; BufferedReader in = null;
PrintWriter out = null; PrintWriter out = null;
...@@ -107,7 +107,7 @@ public class HttpHelper { ...@@ -107,7 +107,7 @@ public class HttpHelper {
String line; String line;
// 读取返回的内容 // 读取返回的内容
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
result += line; result.append(line);
} }
} finally { } finally {
if (out != null) { if (out != null) {
...@@ -117,7 +117,7 @@ public class HttpHelper { ...@@ -117,7 +117,7 @@ public class HttpHelper {
in.close(); in.close();
} }
} }
return result; return result.toString();
} }
/** /**
......
...@@ -2,10 +2,12 @@ package com.yanzuoguang.util.helper; ...@@ -2,10 +2,12 @@ package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.contants.SystemContants; import com.yanzuoguang.util.contants.SystemContants;
import java.util.Random;
import java.util.UUID; import java.util.UUID;
/** /**
* 随机码生成工具 * 随机码生成工具
*
* @author 颜佐光 * @author 颜佐光
*/ */
public final class RandomHelper { public final class RandomHelper {
...@@ -75,7 +77,7 @@ public final class RandomHelper { ...@@ -75,7 +77,7 @@ public final class RandomHelper {
* 随机生成指定字符集、指定长度的的随机码 * 随机生成指定字符集、指定长度的的随机码
* *
* @param charset 基础字符集 * @param charset 基础字符集
* @param len 生成随机码长度 * @param len 生成随机码长度
* @return * @return
*/ */
public static String generateRandomCode(String charset, int len) { public static String generateRandomCode(String charset, int len) {
...@@ -102,12 +104,12 @@ public final class RandomHelper { ...@@ -102,12 +104,12 @@ public final class RandomHelper {
* @return * @return
*/ */
private static String generateRandomCodeOne(String charset, int len) { private static String generateRandomCodeOne(String charset, int len) {
int index = (int) (Math.random() * len); int index = new Random().nextInt(len);
return String.valueOf(charset.charAt(index)); return String.valueOf(charset.charAt(index));
} }
private static String replace(String str, String olds, String news) { private static String replace(String str, String olds, String news) {
if(null == str) { if (null == str) {
return ""; return "";
} }
while (str.indexOf(olds) > -1) { while (str.indexOf(olds) > -1) {
......
...@@ -13,7 +13,7 @@ public class RunHelper { ...@@ -13,7 +13,7 @@ public class RunHelper {
/** /**
* 执行次数 * 执行次数
*/ */
public static int REQ_SIZE = 3; public final static int REQ_SIZE = 3;
/** /**
* 执行次数,并且获取最后一次的异常 * 执行次数,并且获取最后一次的异常
......
...@@ -5,6 +5,7 @@ import com.yanzuoguang.util.exception.CodeException; ...@@ -5,6 +5,7 @@ import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Arrays; import java.util.Arrays;
...@@ -329,31 +330,34 @@ public class StringHelper { ...@@ -329,31 +330,34 @@ public class StringHelper {
* @return 返回获取的值 * @return 返回获取的值
*/ */
public static <T> T to(Class<T> cls, Object from) { public static <T> T to(Class<T> cls, Object from) {
if (from == null) {
return null;
}
String vName = cls.getName(); String vName = cls.getName();
Object to = null; Object to = null;
if (cls.isEnum()) { if (isType(cls, String.class)) {
String strValue = toString(from);
to = EnumHelper.toEnum(cls, strValue);
} else if (isType(cls, String.class)) {
to = toString(from); to = toString(from);
} else if (TYPE_BOOL.equals(vName) || isType(cls, Boolean.class)) { } else if (TYPE_BOOL.equals(vName)
|| (isType(cls, Boolean.class) && from != null)) {
String strValue = toString(from); String strValue = toString(from);
to = toBoolean(strValue); to = toBoolean(strValue);
} else if (TYPE_INT.equals(vName) || isType(cls, Integer.class)) { } else if (TYPE_INT.equals(vName)
|| (isType(cls, Integer.class) && from != null)) {
to = toInt(from); to = toInt(from);
} else if (TYPE_DOUBLE.equals(vName) || isType(cls, Double.class)) { } else if (TYPE_DOUBLE.equals(vName) ||
(isType(cls, Double.class) && from != null)) {
to = toDouble(from); to = toDouble(from);
} else if (TYPE_FLOAT.equals(vName) || isType(cls, Float.class)) { } else if (TYPE_FLOAT.equals(vName)
|| (isType(cls, Float.class) && from != null)) {
to = toDouble(from); to = toDouble(from);
} else if (isType(cls, Double.class)) {
to = toDecimal(from);
} else if (isType(cls, Date.class)) { } else if (isType(cls, Date.class)) {
to = DateHelper.getDateTime(from); to = DateHelper.getDateTime(from);
} else if (cls.isEnum()) {
String strValue = toString(from);
if (strValue != null) {
to = EnumHelper.toEnum(cls, strValue);
}
} }
if (to != null) { if (to == null && from == null) {
return null;
} else if (to != null) {
return (T) to; return (T) to;
} else { } else {
if (ObjectHelper.isSub(cls, from.getClass())) { if (ObjectHelper.isSub(cls, from.getClass())) {
...@@ -572,7 +576,7 @@ public class StringHelper { ...@@ -572,7 +576,7 @@ public class StringHelper {
try { try {
buff = from.getBytes(charset); buff = from.getBytes(charset);
// 将字节流转换为字符串 // 将字节流转换为字符串
from = new String(buff); from = new String(buff, charset);
from = from.replace("\0", "").replace("\n", ""); from = from.replace("\0", "").replace("\n", "");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
ExceptionHelper.handleException(StringHelper.class, e, from); ExceptionHelper.handleException(StringHelper.class, e, from);
...@@ -822,7 +826,7 @@ public class StringHelper { ...@@ -822,7 +826,7 @@ public class StringHelper {
// 生成实现指定摘要算法的 MessageDigest 对象。 // 生成实现指定摘要算法的 MessageDigest 对象。
MessageDigest md = MessageDigest.getInstance("MD5"); MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组更新摘要。 // 使用指定的字节数组更新摘要。
md.update(from.getBytes()); md.update(from.getBytes(Charset.forName("utf-8")));
// 通过执行诸如填充之类的最终操作完成哈希计算。 // 通过执行诸如填充之类的最终操作完成哈希计算。
byte[] b = md.digest(); byte[] b = md.digest();
// 生成具体的md5密码到buf数组 // 生成具体的md5密码到buf数组
......
...@@ -2,7 +2,7 @@ package com.yanzuoguang.util.table; ...@@ -2,7 +2,7 @@ package com.yanzuoguang.util.table;
/** /**
* 列头 * 列头,A.B , A.C
* @author 颜佐光 * @author 颜佐光
*/ */
public class TableHeadItem { public class TableHeadItem {
......
...@@ -16,7 +16,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait ...@@ -16,7 +16,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait
/** /**
* 线程等待间隔 * 线程等待间隔
*/ */
public static int PrintTimeout = 1000 * 2; public final static int PrintTimeout = 1000 * 2;
/** /**
* 线程数量 * 线程数量
...@@ -283,7 +283,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait ...@@ -283,7 +283,7 @@ public abstract class AbstractThreadList<T extends Object> implements ThreadWait
} }
ThreadListData<T> data = cacheThread.get(Thread.currentThread()); ThreadListData<T> data = cacheThread.get(Thread.currentThread());
data.setDate(new Date()); data.setDate(System.currentTimeMillis());
data.setData(item); data.setData(item);
try { try {
this.run(item); this.run(item);
......
...@@ -10,6 +10,7 @@ import java.util.List; ...@@ -10,6 +10,7 @@ import java.util.List;
/** /**
* 自动执行任务 * 自动执行任务
*
* @author 颜佐光 * @author 颜佐光
*/ */
public class RunPlan { public class RunPlan {
...@@ -82,7 +83,7 @@ public class RunPlan { ...@@ -82,7 +83,7 @@ public class RunPlan {
*/ */
public final void run(boolean isRemove, int maxError) { public final void run(boolean isRemove, int maxError) {
for (int i = list.size() - 1; i >= 0; i--) { for (int i = list.size() - 1; i >= 0; i--) {
Date now = new Date(); long now = System.currentTimeMillis();
RunPlanData item; RunPlanData item;
synchronized (this.lock) { synchronized (this.lock) {
item = list.size() > i ? list.get(i) : null; item = list.size() > i ? list.get(i) : null;
...@@ -96,10 +97,10 @@ public class RunPlan { ...@@ -96,10 +97,10 @@ public class RunPlan {
// 在Window CE中时间相减可能会出错 // 在Window CE中时间相减可能会出错
try { try {
// 处理非法改动时间 // 处理非法改动时间
if (item.getDate().compareTo(now) > 0) { if (item.getDate() > now) {
item.setDate(now); item.setDate(now);
} }
millSeconds = (now.getTime() - item.getDate().getTime()); millSeconds = (now - item.getDate());
} catch (Exception ex) { } catch (Exception ex) {
ExceptionHelper.handleException(ThreadHelper.class, ex); ExceptionHelper.handleException(ThreadHelper.class, ex);
} }
......
...@@ -10,7 +10,7 @@ public class RunPlanData { ...@@ -10,7 +10,7 @@ public class RunPlanData {
/** /**
* 任务开始时间 * 任务开始时间
*/ */
private Date date; private long date;
/** /**
* 执行标记 * 执行标记
*/ */
...@@ -39,11 +39,11 @@ public class RunPlanData { ...@@ -39,11 +39,11 @@ public class RunPlanData {
this.initDate(); this.initDate();
} }
public Date getDate() { public long getDate() {
return date; return date;
} }
public void setDate(Date date) { public void setDate(long date) {
this.date = date; this.date = date;
} }
...@@ -106,6 +106,6 @@ public class RunPlanData { ...@@ -106,6 +106,6 @@ public class RunPlanData {
* 重置时间 * 重置时间
*/ */
public void initDate() { public void initDate() {
this.date = new Date(); this.date = System.currentTimeMillis();
} }
} }
...@@ -17,7 +17,7 @@ public final class RunnableListAuto { ...@@ -17,7 +17,7 @@ public final class RunnableListAuto {
/** /**
* 是否打印线程日志 * 是否打印线程日志
*/ */
public static boolean IsLog = false; public final static boolean IsLog = false;
/** /**
* 缓存的执行对象的数据大小 * 缓存的执行对象的数据大小
......
...@@ -13,18 +13,18 @@ public class ThreadListData<T> { ...@@ -13,18 +13,18 @@ public class ThreadListData<T> {
/** /**
* 执行时间 * 执行时间
*/ */
private Date date; private long date;
/** /**
* 执行的数据 * 执行的数据
*/ */
private T data; private T data;
public Date getDate() { public long getDate() {
return date; return date;
} }
public void setDate(Date date) { public void setDate(long date) {
this.date = date; this.date = date;
} }
......
...@@ -3,11 +3,15 @@ package com.yanzuoguang.util.vo; ...@@ -3,11 +3,15 @@ package com.yanzuoguang.util.vo;
/** /**
* 引用值,方便修改 * 引用值,方便修改
* *
int func(Ref<Interger> int1,Ref<Integer> int2){
int1.value =1 ;
}
* @param <T> * @param <T>
* @author 颜佐光 * @author 颜佐光
*/ */
public class Ref<T> { public class Ref<T> {
public T value; public T value;
public Ref(T value) { public Ref(T value) {
this.value = value; this.value = value;
} }
......
...@@ -2,7 +2,6 @@ package com.yanzuoguang.cloud.aop; ...@@ -2,7 +2,6 @@ package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.cloud.CloudContans; import com.yanzuoguang.cloud.CloudContans;
import com.yanzuoguang.cloud.service.TokenServiceCall; import com.yanzuoguang.cloud.service.TokenServiceCall;
import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.contants.ResultConstants; import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.JsonHelper; import com.yanzuoguang.util.helper.JsonHelper;
...@@ -20,6 +19,7 @@ import org.aspectj.lang.reflect.MethodSignature; ...@@ -20,6 +19,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
...@@ -42,6 +42,9 @@ public class WebAspect extends BaseRequestAspect { ...@@ -42,6 +42,9 @@ public class WebAspect extends BaseRequestAspect {
@Autowired @Autowired
private TokenServiceCall tokenServiceCall; private TokenServiceCall tokenServiceCall;
@Value("${yzg.reqUrl:order,check,use}")
private String reqUrl;
/** /**
* exec aop point aspect * exec aop point aspect
*/ */
...@@ -116,30 +119,55 @@ public class WebAspect extends BaseRequestAspect { ...@@ -116,30 +119,55 @@ public class WebAspect extends BaseRequestAspect {
* @throws NoSuchMethodException * @throws NoSuchMethodException
*/ */
private Type getReturnType(ProceedingJoinPoint joinPoint) { private Type getReturnType(ProceedingJoinPoint joinPoint) {
Method m = getMethod(joinPoint);
Type t = m.getAnnotatedReturnType().getType();
return t;
}
/**
* 获取返回的至类型
*
* @param joinPoint
* @return
* @throws NoSuchMethodException
*/
private Method getMethod(ProceedingJoinPoint joinPoint) {
//获取返回值类型 //获取返回值类型
Signature s = joinPoint.getSignature(); Signature s = joinPoint.getSignature();
MethodSignature ms = (MethodSignature) s; MethodSignature ms = (MethodSignature) s;
Method m = ms.getMethod(); Method m = ms.getMethod();
Type t = m.getAnnotatedReturnType().getType(); return m;
return t;
} }
/**
* 执行方法
*
* @param joinPoint 需要执行的方法
* @param name 方法名称
* @return 返回结果
* @throws Throwable
*/
private Object executeMethod(ProceedingJoinPoint joinPoint, String name) throws Throwable { private Object executeMethod(ProceedingJoinPoint joinPoint, String name) throws Throwable {
boolean dataArgs = joinPoint.getArgs().length != 1 boolean dataArgs = joinPoint.getArgs().length != 1
|| joinPoint.getArgs().length == 1 && || joinPoint.getArgs().length == 1 &&
(joinPoint.getArgs()[0] instanceof ServletResponse || joinPoint.getArgs()[0] instanceof ServletRequest); (joinPoint.getArgs()[0] instanceof ServletResponse || joinPoint.getArgs()[0] instanceof ServletRequest);
if (dataArgs) { Method method = getMethod(joinPoint);
boolean isUrl = false;
if (!StringHelper.isEmpty(reqUrl)) {
String[] urls = reqUrl.split(",");
for (String url : urls) {
if (method.getName().matches(url)) {
isUrl = true;
break;
}
}
}
if (dataArgs || !isUrl) {
return joinPoint.proceed(); return joinPoint.proceed();
} else { } else {
// 获取请求编号 // 获取请求编号
Object firstArgs = joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null; Object firstArgs = joinPoint.getArgs().length > 0 ? joinPoint.getArgs()[0] : null;
String reqId = ObjectHelper.getString(firstArgs, "reqId"); String reqId = StringHelper.md5(JsonHelper.serialize(firstArgs));
if (StringHelper.isEmpty(reqId)) {
reqId = StringHelper.md5(JsonHelper.serialize(firstArgs));
} else {
// 请求编号和公司编号挂钩
reqId = StringHelper.getId(ObjectHelper.getString(firstArgs, "companyId"), reqId);
}
String reqFull = StringHelper.getId(reqId, HttpAspectUtil.getHttpRequestUrl()); String reqFull = StringHelper.getId(reqId, HttpAspectUtil.getHttpRequestUrl());
RequestCacheResult req = cacheResult.get(reqFull, new RequestCacheResult(reqFull)); RequestCacheResult req = cacheResult.get(reqFull, new RequestCacheResult(reqFull));
// 缓存的键值对 // 缓存的键值对
......
package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.util.log.Log;
import org.springframework.boot.web.servlet.filter.OrderedHiddenHttpMethodFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 跨域的支持
*
* @author 颜佐光
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
Log.info(WebConfig.class, "跨域已开启支持");
}
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, response);
}
};
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
...@@ -10,6 +10,7 @@ import java.util.Random; ...@@ -10,6 +10,7 @@ import java.util.Random;
/** /**
* 加密算法0版实现 * 加密算法0版实现
*
* @author 颜佐光 * @author 颜佐光
*/ */
public class CodePwdImpl implements CodePwd { public class CodePwdImpl implements CodePwd {
...@@ -38,25 +39,26 @@ public class CodePwdImpl implements CodePwd { ...@@ -38,25 +39,26 @@ public class CodePwdImpl implements CodePwd {
*/ */
@Override @Override
public String getCode(String rand, String day, String index, String pwd) { public String getCode(String rand, String day, String index, String pwd) {
String ret = ""; StringBuilder ret = new StringBuilder();
// 1. 将随即数和天数进行组合生成字符串 // 1. 将随即数和天数进行组合生成字符串
String randDay = ""; StringBuilder sb = new StringBuilder();
{ {
int randSize = rand.length(); int randSize = rand.length();
int daySize = day.length(); int daySize = day.length();
int maxLen = Math.max(rand.length(), day.length()); int maxLen = Math.max(rand.length(), day.length());
for (int i = 0; i < maxLen; i++) { for (int i = 0; i < maxLen; i++) {
if (i < daySize) { if (i < daySize) {
randDay += day.charAt(i); sb.append(day.charAt(i));
} }
if (i < randSize) { if (i < randSize) {
randDay += rand.charAt(i); sb.append(rand.charAt(i));
} }
} }
} }
// 2. 将组合后的数字进行交换 // 2. 将组合后的数字进行交换
String randDay = sb.toString();
int randDaySize = randDay.length(); int randDaySize = randDay.length();
char[] dayChars = new char[randDaySize]; char[] dayChars = new char[randDaySize];
{ {
...@@ -71,7 +73,7 @@ public class CodePwdImpl implements CodePwd { ...@@ -71,7 +73,7 @@ public class CodePwdImpl implements CodePwd {
} }
} }
for (int i = 0; i < randDaySize; i++) { for (int i = 0; i < randDaySize; i++) {
ret += dayChars[i]; ret.append(dayChars[i]);
} }
} }
...@@ -121,10 +123,10 @@ public class CodePwdImpl implements CodePwd { ...@@ -121,10 +123,10 @@ public class CodePwdImpl implements CodePwd {
for (int i = 0; i < newSize; i++) { for (int i = 0; i < newSize; i++) {
newValue[i] = (newValue[i] % 10 + 10) % 10; newValue[i] = (newValue[i] % 10 + 10) % 10;
ret += newValue[i]; ret.append(newValue[i]);
} }
return ret; return ret.toString();
} }
public static void test(String[] args) { public static void test(String[] args) {
......
package com.yanzuoguang.dao; package com.yanzuoguang.dao;
import com.yanzuoguang.util.vo.PageSizeData;
import com.yanzuoguang.util.vo.PageSizeReqVo;
import java.util.List; import java.util.List;
/** /**
* 数据基本操作接口 * 数据基本操作接口
*
* @author 颜佐光 * @author 颜佐光
*/ */
public interface BaseDao { public interface BaseDao {
...@@ -35,31 +39,41 @@ public interface BaseDao { ...@@ -35,31 +39,41 @@ public interface BaseDao {
String save(Object model); String save(Object model);
/** /**
* 删除数据 * 删除数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.remove({orderId:1});
* * int field;
* @param model 需要删除的数据 * @param model 需要删除的数据,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @return 删除的记录数量 * @return 删除的记录数量
*/ */
int remove(Object model); int remove(Object model);
/** /**
* 加载数据 * 加载数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.load({orderId:1});
* *
* @param model 加载数据的请求参数 * @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param cls 需要加载的数据的类型 * @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型 * @param <T> 返回数据的类型
* @return 需要返回的数据 * @return 需要返回的数据
*/ */
<T extends Object> T load(Object model, Class<T> cls); <T extends Object> T load(Object model, Class<T> resultClass);
/** /**
* 加载列表数据 * 加载列表数据,可以用于父子表删除,如通过订单删除游客信息 visitorDao.loadList({orderId:1});
*
* @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
<T extends Object> List<T> loadList(Object model, Class<T> resultClass);
/**
* 加载分页数据
* *
* @param model 加载数据的请求参数 * @param model 加载数据的请求参数,可以是主键字符串(Int),或者是包含主键的实体,或者是包含其他非主键的实体完全匹配.
* @param cls 需要加载的数据的类型 * @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型 * @param <T> 返回数据的类型
* @return 需要返回的数据 * @return 需要返回的数据
*/ */
<T extends Object> List<T> loadList(Object model, Class<T> cls); <T extends Object> PageSizeData<T> loadPage(PageSizeReqVo model, Class<T> resultClass);
} }
...@@ -53,6 +53,11 @@ public class DaoConst { ...@@ -53,6 +53,11 @@ public class DaoConst {
*/ */
public static final String GROUP_QUERY = "GroupQuery"; public static final String GROUP_QUERY = "GroupQuery";
/**
* 根据某个字段保存
*/
public static final String SAVE_WITH = "SaveWith";
/** /**
* 驼峰式命名 * 驼峰式命名
*/ */
...@@ -69,51 +74,119 @@ public class DaoConst { ...@@ -69,51 +74,119 @@ public class DaoConst {
* 单位地址 * 单位地址
*/ */
public static final int CODE_UNIT = 2; public static final int CODE_UNIT = 2;
/**
* 插入SQL语句模板
*/
public static final String SQL_INSERT = "INSERT INTO {TABLE}({FIELD}) VALUES({VALUES})";
/**
* 更新SQL语句模板
*/
public static final String SQL_UPDATE = "UPDATE {TABLE} AS a {INNER} SET {FIELD} WHERE 1=1 {WHERE}";
/**
* 删除SQL语句模板
*/
public static final String SQL_REMOVE = "DELETE a FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}";
/**
* 加载SQL语句模板
*/
public static final String SQL_LOAD = "SELECT a.*{FIELD} FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}";
/** /**
* 表名代码片段 * 表名代码片段
*/ */
public static final String TABLE_CODE = "{TABLE}"; public static final String CODE_TABLE = "{TABLE}";
/** /**
* 字段代码片段 * 字段代码片段
*/ */
public static final String FIELD_CODE = "{FIELD}"; public static final String CODE_FIELD = "{FIELD}";
/** /**
* 值代码片段 * 值代码片段
*/ */
public static final String VALUES_CODE = "{VALUES}"; public static final String CODE_VALUES = "{VALUES}";
/** /**
* WHERE条件代码片段 * WHERE条件代码片段
*/ */
public static final String WHERE_CODE = "{WHERE}"; public static final String CODE_WHERE = "{WHERE}";
/** /**
* 插入SQL语句模板 * 更新字段模板
*/ */
public static final String INSERT_MODEL = "INSERT INTO {TABLE}({FIELD}) VALUES({VALUES})"; public static final String CODE_UPDATE_FIELD = "a.%s=%s";
/** /**
* 更新SQL语句模板 * 更新字段模板主键
*/ */
public static final String UPDATE_MODEL = "UPDATE {TABLE} SET {FIELD} WHERE 1=1 {WHERE}"; public static final String CODE_UPDATE_PRIMARY = "a.%s=a.%s";
/** /**
* 删除SQL语句模板 * 更新字段模板参数
*/ */
public static final String REMOVE_MODEL = "DELETE FROM {TABLE} WHERE 1=1 {WHERE}"; public static final String CODE_UPDATE_FIELD_PARA = ",a.%s=?";
/** /**
* 加载SQL语句模板 * 更新字段模板参数
*/
public static final String CODE_UPDATE_FIELD_REMOVE = "a.%s=1";
/**
* 等于条件
*/ */
public static final String LOAD_MODEL = "SELECT a.*{FIELD} FROM {TABLE} AS a {INNER} WHERE 1=1 {WHERE}"; public static final String CODE_WHERE_EQUALS = "AND %s%s=%s";
/**
* 等于条件参数
*/
public static final String CODE_WHERE_EQUALS_PARA = "AND a.%s=?";
/**
* 未删除条件
*/
public static final String CODE_WHERE_EQUALS_NOT_REMOVE = "AND a.%s=0";
/**
* 版本好字段
*/
public static final String CODE_UPDATE_VERSION_FIELD = ",a.%s=1+a.%s";
/**
* 不等于条件
*/
public static final String CODE_WHERE_NOT_EQUALS = "AND %s%s<>%s";
/**
* 不等于条件
*/
public static final String CODE_WHERE_NOT_EQUALS_PARA = "AND a.%s<>?";
/**
* 默认表标记
*/
public static final String CODE_TAG = "a.";
/**
* 参数标记
*/
public static final String CODE_PARA = "?";
/**
* 增加修改语句的分割符号
*/
public static final String CODE_SPLIT = ",";
/**
* 统计语句增加字段模板
*/
public static final String CODE_GROUP_ADD = "a.{FIELD}=a.{FIELD}+?";
/** /**
* 版本号字段名称 * 版本号字段名称
*/ */
public static final String VERSON = "verson"; public static final String VERSION_FLAG = "version";
/** /**
* 删除字段名称 * 删除字段名称
*/ */
public static final String ISREMOVE = "isremove"; public static final String REMOVE_FLAG = "remove";
/**
* 创建字段名称
*/
public static final String CREATE_FLAG = "create";
/**
* 更新字段名称
*/
public static final String UPDATE_FLAG = "update";
/**
* MD5标记字段
*/
public static final String MD5_KEY_FLAG = "md5key";
/** /**
* 删除字符串长度变量 * 删除字符串长度变量
*/ */
public static final String ISREMOVE_CONTANS = "contans____isremove"; public static final String REMOVE_FLAG_INPUT = "remove_input";
/** /**
* ID字段 * ID字段
*/ */
...@@ -122,4 +195,85 @@ public class DaoConst { ...@@ -122,4 +195,85 @@ public class DaoConst {
* 集合初始化大小 * 集合初始化大小
*/ */
public static final int COLLECTION_INIT_SIZE = 15; public static final int COLLECTION_INIT_SIZE = 15;
/**
* 查询条件默认代码片段
*/
public static final String[] LAST_AUTO_ADD = new String[]{"{WHERE}", "{GROUP}", "{HAVING}", "{ORDER}", "{LIMIT}"};
/**
* 普通字段
*/
public static final int FIELD_NONE = -1;
/**
* 普通字段
*/
public static final int FIELD_COMMON = 0;
/**
* 删除标记
*/
public static final int FIELD_REMOVE = 1;
/**
* 版本号字段
*/
public static final int FIELD_VERSION = 2;
/**
* 主键字段
*/
public static final int FIELD_PRIMARY = 3;
/**
* MD5标记字段,用于统计字段
*/
public static final int FIELD_MD5 = 4;
/**
* 删除时记录操作状态的字段
*/
public static final int FIELD_REMOVE_UPDATE = 5;
/**
* 删除时记录操作状态的字段
*/
public static final int FIELD_CREATE = 6;
/**
* 根据字段保存
*/
public static final int FIELD_SAVE_WITH = 7;
/**
* 根据字段添加统计
*/
public static final int FIELD_ADD_GROUP = 8;
/**
* SQL语句类型-普通语句
*/
public static final int SQL_TYPE_COMMON = 0;
/**
* SQL语句类型-创建语句
*/
public static final int SQL_TYPE_CREATE = 1;
/**
* SQL语句类型-更新语句
*/
public static final int SQL_TYPE_UPDATE = 2;
/**
* SQL语句类型-删除语句
*/
public static final int SQL_TYPE_REMOVE = 3;
/**
* SQL语句类型-加载语句
*/
public static final int SQL_TYPE_LOAD = 4;
/**
* SQL语句类型-是否存在
*/
public static final int SQL_TYPE_EXISTS = 5;
/**
* SQL语句类型-根据字段保存
*/
public static final int SQL_TYPE_SAVE_WITH = 6;
/**
* SQL语句类型-添加统计
*/
public static final int SQL_TYPE_ADD_GROUP = 7;
} }
package com.yanzuoguang.dao; package com.yanzuoguang.dao;
import com.yanzuoguang.util.helper.StringHelper;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
...@@ -18,5 +20,11 @@ public @interface TableAnnotation { ...@@ -18,5 +20,11 @@ public @interface TableAnnotation {
* *
* @return * @return
*/ */
String value(); String value() default StringHelper.EMPTY;
/**
* 字段类型
* @return
*/
int type() default DaoConst.FIELD_NONE;
} }
...@@ -2,18 +2,21 @@ package com.yanzuoguang.dao.impl; ...@@ -2,18 +2,21 @@ package com.yanzuoguang.dao.impl;
import com.yanzuoguang.dao.BaseDao; import com.yanzuoguang.dao.BaseDao;
import com.yanzuoguang.dao.DaoConst; import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.db.impl.AllBeanRowMapper;
import com.yanzuoguang.util.base.ObjectHelper; import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.exception.CodeException; import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.DateHelper; import com.yanzuoguang.util.helper.DateHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.vo.InitDao; import com.yanzuoguang.util.vo.*;
import com.yanzuoguang.util.vo.MapRow;
import java.util.*; import java.util.*;
/** /**
* 数据库操作的基本工具类 * 数据库操作的基本工具类
* 1. 实现了基本的增删该查
* 2. 实现了统计的增肌和修改
* 3. 实现了一定功能的基本验证,验证数据是否存在
* 4. 数据主键的获取等功能。
* 5. 获取自增等功能
* *
* @author 颜佐光 * @author 颜佐光
*/ */
...@@ -145,6 +148,9 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -145,6 +148,9 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
this.check(DaoConst.OPERATOR_TYPE_UPDATE, keyString, model); this.check(DaoConst.OPERATOR_TYPE_UPDATE, keyString, model);
SqlData sqlData = this.getSql(DaoConst.UPDATE); SqlData sqlData = this.getSql(DaoConst.UPDATE);
int ret = updateSql(sqlData, model); int ret = updateSql(sqlData, model);
if (ret == 0) {
throw new CodeException("修改失败,请确认是否被其他人修改,版本号传入是否正确");
}
String retVal = ret > 0 ? keyString : ""; String retVal = ret > 0 ? keyString : "";
return retVal; return retVal;
} }
...@@ -161,6 +167,14 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -161,6 +167,14 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
InitDao to = (InitDao) model; InitDao to = (InitDao) model;
to.init(); to.init();
} }
if (operatorType == DaoConst.OPERATOR_TYPE_CREATE || operatorType == DaoConst.OPERATOR_TYPE_UPDATE) {
List<SqlData> sqlArray = this.table.getSqlType(DaoConst.SQL_TYPE_SAVE_WITH);
if (sqlArray != null) {
for (SqlData sql : sqlArray) {
this.checkExist(sql.getName(), model, String.format("%s已经存在", sql.getName()));
}
}
}
} }
/** /**
...@@ -197,16 +211,12 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -197,16 +211,12 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
this.setKeyString(from, keyString); this.setKeyString(from, keyString);
// 调用删除日志 // 调用删除日志
this.check(DaoConst.OPERATOR_TYPE_REMOVE, keyString, from); this.check(DaoConst.OPERATOR_TYPE_REMOVE, keyString, from);
} else { }
List<MapRow> rows = this.query(MapRow.class, DaoConst.LOAD, from);
for (MapRow row : rows) { // 处理来源值
keyString = this.getKeyString(from); for (TableFieldVo fieldVo : this.table.getTable().getRemoveUpdate()) {
if (StringHelper.isEmpty(keyString)) { Object fromValue = ObjectHelper.get(model, fieldVo.inputName);
keyString = StringHelper.toString(AllBeanRowMapper.getLoweRowField(row, this.getKey())); ObjectHelper.set(from, fieldVo.inputName, fromValue);
}
// 调用删除日志
this.check(DaoConst.OPERATOR_TYPE_REMOVE, keyString, row);
}
} }
// 调用删除语句 // 调用删除语句
...@@ -217,13 +227,13 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -217,13 +227,13 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
/** /**
* 加载数据 * 加载数据
* *
* @param model 加载数据的请求参数 * @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型 * @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型 * @param <T> 返回数据的类型
* @return 需要返回的数据 * @return 需要返回的数据
*/ */
@Override @Override
public <T extends Object> T load(Object model, Class<T> cls) { public <T extends Object> T load(Object model, Class<T> resultClass) {
// 获取来源主键 // 获取来源主键
Object from = model; Object from = model;
String key = this.getInputKey(from); String key = this.getInputKey(from);
...@@ -235,7 +245,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -235,7 +245,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
} }
// 通过传入数据进行加载 // 通过传入数据进行加载
T to = this.queryFirst(cls, DaoConst.LOAD, from); T to = this.queryFirst(resultClass, DaoConst.LOAD, from);
if (to == null) { if (to == null) {
return to; return to;
} }
...@@ -254,13 +264,13 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -254,13 +264,13 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
/** /**
* 加载数据 * 加载数据
* *
* @param model 加载数据的请求参数 * @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型 * @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型 * @param <T> 返回数据的类型
* @return 需要返回的数据 * @return 需要返回的数据
*/ */
@Override @Override
public <T extends Object> List<T> loadList(Object model, Class<T> cls) { public <T extends Object> List<T> loadList(Object model, Class<T> resultClass) {
// 获取来源主键 // 获取来源主键
Object from = model; Object from = model;
String key = this.getInputKey(from); String key = this.getInputKey(from);
...@@ -272,7 +282,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -272,7 +282,7 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
} }
// 通过传入数据进行加载 // 通过传入数据进行加载
List<T> to = this.query(cls, DaoConst.LOAD, from); List<T> to = this.query(resultClass, DaoConst.LOAD, from);
if (to == null || to.size() == 0) { if (to == null || to.size() == 0) {
return new ArrayList<>(); return new ArrayList<>();
} }
...@@ -290,6 +300,46 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao { ...@@ -290,6 +300,46 @@ public abstract class BaseDaoImpl extends BaseDaoSql implements BaseDao {
return to; return to;
} }
/**
* 加载分页数据
*
* @param model 加载数据的请求参数
* @param resultClass 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
@Override
public <T extends Object> PageSizeData<T> loadPage(PageSizeReqVo model, Class<T> resultClass) {
// 获取来源主键
Object from = model;
String key = this.getInputKey(from);
// 当主键存在时,只通过主键加载
if (!StringHelper.isEmpty(key)) {
from = new HashMap<String, Object>(DaoConst.COLLECTION_INIT_SIZE);
this.setKeyString(from, key);
}
// 通过传入数据进行加载
PageSizeData<T> to = this.queryPage(resultClass, model, DaoConst.LOAD, from);
if (to == null || to.getPageTotal() == 0) {
return to;
}
// 判断来源主键是否存在,不存在则获取加载后的主键
if (StringHelper.isEmpty(key)) {
check(DaoConst.OPERATOR_TYPE_LOAD, key, to);
} else {
for (Object item : to.getList()) {
key = this.getKeyString(item);
check(DaoConst.OPERATOR_TYPE_LOAD, key, to);
}
}
return to;
}
/** /**
* 添加统计数据 * 添加统计数据
* *
......
...@@ -19,7 +19,7 @@ import java.util.regex.Matcher; ...@@ -19,7 +19,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* SQL语句基本操作类 * SQL语句基本操作类,包括SQL语句的解析,参数的组装,查询缓存的处理
* *
* @author 颜佐光 * @author 颜佐光
*/ */
...@@ -44,7 +44,7 @@ public abstract class BaseDaoSql { ...@@ -44,7 +44,7 @@ public abstract class BaseDaoSql {
/** /**
* 缓存的表结构和SQL语句 * 缓存的表结构和SQL语句
*/ */
protected static MemoryCache<TableSqlCache> cache = new MemoryCache<>(); protected final static MemoryCache<TableSqlCache> cache = new MemoryCache<>();
/** /**
* 获取数据库执行类 * 获取数据库执行类
...@@ -131,7 +131,7 @@ public abstract class BaseDaoSql { ...@@ -131,7 +131,7 @@ public abstract class BaseDaoSql {
if (this.table == null) { if (this.table == null) {
throw new CodeException("类" + this.getClass().getName() + "未发现表结构"); throw new CodeException("类" + this.getClass().getName() + "未发现表结构");
} }
SqlData sql = this.table.getSqls().get(name); SqlData sql = this.table.getNameCache().get(name);
if (isThrow && sql == null) { if (isThrow && sql == null) {
throw new CodeException("类" + this.getClass().getName() + "未发现SQL语句" + name); throw new CodeException("类" + this.getClass().getName() + "未发现SQL语句" + name);
} }
...@@ -186,7 +186,7 @@ public abstract class BaseDaoSql { ...@@ -186,7 +186,7 @@ public abstract class BaseDaoSql {
protected Object queryCell(SqlData sqlData, Object model) { protected Object queryCell(SqlData sqlData, Object model) {
List<Object> paras = new ArrayList<>(); List<Object> paras = new ArrayList<>();
String sql = this.getQueryPara(paras, sqlData, model); String sql = this.getQueryPara(paras, sqlData, model);
Object cell = this.queryCellWithCache(sql, sqlData.getName(), paras.toArray()); Object cell = this.queryCellWithCache(sqlData.getName(), sql, paras.toArray());
return cell; return cell;
} }
...@@ -412,20 +412,19 @@ public abstract class BaseDaoSql { ...@@ -412,20 +412,19 @@ public abstract class BaseDaoSql {
* @return SQL条件 * @return SQL条件
*/ */
protected String getQueryPara(List<Object> paras, SqlData sqlData, Object model) { protected String getQueryPara(List<Object> paras, SqlData sqlData, Object model) {
// 定义可替换片段
String[] lastCode = new String[]{"{WHERE}", "{GROUP}", "{HAVING}", "{ORDER}", "{LIMIT}"};
// 将SQL语句进行代码片段追加 // 将SQL语句进行代码片段追加
String sql = sqlData.getSql(); StringBuilder sb = new StringBuilder(sqlData.getSql());
for (String code : lastCode) { for (String code : DaoConst.LAST_AUTO_ADD) {
if (sql.indexOf(code) == -1) { if (sb.indexOf(code) == -1) {
sql += code; sb.append(code);
} }
} }
// 代码片段缓存 // 代码片段缓存
Map<String, List<String>> codeMap = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE); Map<String, List<String>> codeMap = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
// 处理字段以及代码片段 // 处理字段以及代码片段
String sql = sb.toString();
sql = handleCodeRelease(sql, sqlData, model, codeMap); sql = handleCodeRelease(sql, sqlData, model, codeMap);
sql = handleCodeReplace(sql, codeMap); sql = handleCodeReplace(sql, codeMap);
...@@ -548,7 +547,7 @@ public abstract class BaseDaoSql { ...@@ -548,7 +547,7 @@ public abstract class BaseDaoSql {
*/ */
private Object getParaValue(Object val) { private Object getParaValue(Object val) {
if (val instanceof Boolean) { if (val instanceof Boolean) {
val = 0; val = (Boolean)val ? 1 : 0;
} }
val = StringHelper.toString(val); val = StringHelper.toString(val);
return val; return val;
...@@ -682,7 +681,7 @@ public abstract class BaseDaoSql { ...@@ -682,7 +681,7 @@ public abstract class BaseDaoSql {
} }
// 将对象转换为 Map 对象 // 将对象转换为 Map 对象
Map to = new HashMap<String, Object>(DaoConst.COLLECTION_INIT_SIZE); Map<String, Object> to = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
if (from instanceof Map) { if (from instanceof Map) {
to = (Map) from; to = (Map) from;
} else { } else {
...@@ -694,16 +693,16 @@ public abstract class BaseDaoSql { ...@@ -694,16 +693,16 @@ public abstract class BaseDaoSql {
sb.append(" SELECT "); sb.append(" SELECT ");
// 处理列 // 处理列
for (Object oItemKey : to.keySet()) { for (Map.Entry<String, Object> oItemKey : to.entrySet()) {
if (column > 0) { if (column > 0) {
sb.append(","); sb.append(",");
} }
String itemKey = StringHelper.toString(oItemKey); String itemKey = oItemKey.getKey();
sb.append("? AS " + itemKey); sb.append("? AS " + itemKey);
// 处理参数 // 处理参数
Object itemValue = to.get(oItemKey); Object itemValue = oItemKey.getValue();
itemValue = this.getParaValue(itemValue); itemValue = this.getParaValue(itemValue);
paras.add(itemValue); paras.add(itemValue);
column++; column++;
......
...@@ -12,9 +12,9 @@ import java.util.List; ...@@ -12,9 +12,9 @@ import java.util.List;
public class SqlData { public class SqlData {
/** /**
* 对应的参数顺序 * SQL语句类型
*/ */
private List<SqlDataField> sqlDataFields = new ArrayList<SqlDataField>(); private int sqlType = DaoConst.SQL_TYPE_COMMON;
/** /**
* SQL语句的名称 * SQL语句的名称
...@@ -26,6 +26,11 @@ public class SqlData { ...@@ -26,6 +26,11 @@ public class SqlData {
*/ */
private String sql; private String sql;
/**
* 对应的参数顺序
*/
private List<SqlDataField> sqlDataFields = new ArrayList<SqlDataField>();
/** /**
* 构造函数 * 构造函数
*/ */
...@@ -33,6 +38,22 @@ public class SqlData { ...@@ -33,6 +38,22 @@ public class SqlData {
this("", ""); this("", "");
} }
/**
* Sql语句类型
* @return Sql语句类型
*/
public int getSqlType() {
return sqlType;
}
/**
* Sql语句类型
* @param sqlType Sql语句类型
*/
public void setSqlType(int sqlType) {
this.sqlType = sqlType;
}
public List<SqlDataField> getSqlDataFields() { public List<SqlDataField> getSqlDataFields() {
return sqlDataFields; return sqlDataFields;
} }
...@@ -231,7 +252,7 @@ public class SqlData { ...@@ -231,7 +252,7 @@ public class SqlData {
* @return * @return
*/ */
public SqlData removeFieldRemove() { public SqlData removeFieldRemove() {
this.removeField(DaoConst.ISREMOVE_CONTANS); this.removeField(DaoConst.REMOVE_FLAG_INPUT);
return this; return this;
} }
......
package com.yanzuoguang.dao.impl; package com.yanzuoguang.dao.impl;
import com.yanzuoguang.util.helper.StringHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -12,9 +14,11 @@ public class SqlDataField { ...@@ -12,9 +14,11 @@ public class SqlDataField {
/** /**
* 前台参数名称,当没有前台参数时,则把当前字段当常量代码片段处理 * 前台参数名称,当没有前台参数时,则把当前字段当常量代码片段处理
*/ */
public String paraName = ""; public String paraName = StringHelper.EMPTY;
/** /**
* 是否根据前台参数自动添加,false时保持永久添加模式 * 是否根据前台参数自动添加,false时保持永久添加模式,
* 1. true为条件模式,即前台不输入参数时,则不增加相关代码片段
* 2. false为敞亮模式,不管前台是否输入,该参数和片段必然会增加到后台执行语句中
*/ */
public boolean auto = true; public boolean auto = true;
/** /**
......
...@@ -28,14 +28,28 @@ public class TableFieldVo { ...@@ -28,14 +28,28 @@ public class TableFieldVo {
this.type = type; this.type = type;
} }
/**
* 表字段的原名称
*/
public String name; public String name;
/**
* 表子弹的名称小写
*/
public String lName; public String lName;
/**
* 前台输入参数的名称
*/
public String inputName; public String inputName;
/**
* 前台输入的参数的小写
*/
public String inputLName; public String inputLName;
/**
* 实体的参数的类型
*/
public Class<?> type = String.class; public Class<?> type = String.class;
;
} }
...@@ -14,6 +14,7 @@ import java.util.regex.Pattern; ...@@ -14,6 +14,7 @@ import java.util.regex.Pattern;
/** /**
* 缓存的SQL语句信息 * 缓存的SQL语句信息
*
* @author 颜佐光 * @author 颜佐光
*/ */
public class TableSqlCache { public class TableSqlCache {
...@@ -24,14 +25,19 @@ public class TableSqlCache { ...@@ -24,14 +25,19 @@ public class TableSqlCache {
public static final String PAGE_SIZE_TAG = "_PageSize"; public static final String PAGE_SIZE_TAG = "_PageSize";
/** /**
* 表信息 * 表结构信息
*/ */
private TableStruct table; private TableStruct table;
/** /**
* 缓存的SQL信息 * 缓存的SQL信息,按照名称进行缓存
*/ */
private MemoryCache<SqlData> sqls = new MemoryCache<SqlData>(); private MemoryCache<SqlData> nameCache = new MemoryCache<SqlData>();
/**
* 根据Sql语句类型进行缓存,按照类型进行缓存
*/
private MemoryCache<List<SqlData>> typeCache = new MemoryCache<>();
/** /**
* 构造函数 * 构造函数
...@@ -58,11 +64,25 @@ public class TableSqlCache { ...@@ -58,11 +64,25 @@ public class TableSqlCache {
*/ */
public SqlData add(SqlData sql) { public SqlData add(SqlData sql) {
if (sql != null) { if (sql != null) {
this.sqls.put(sql.getName(), sql); this.nameCache.put(sql.getName(), sql);
String keyType = String.valueOf(sql.getSqlType());
this.typeCache.get(keyType, new ArrayList<>()).add(sql);
} }
return sql; return sql;
} }
/**
* 获取所有的Sql语句执行类型
*
* @param sqlType Sql语句执行类型
* @return Sql语句列表
*/
public List<SqlData> getSqlType(int sqlType) {
String keyType = String.valueOf(sqlType);
return typeCache.get(keyType);
}
/** /**
* 添加SQL * 添加SQL
* *
...@@ -278,8 +298,8 @@ public class TableSqlCache { ...@@ -278,8 +298,8 @@ public class TableSqlCache {
} }
private String replaceString(Map<String, StringBuilder> map, String sql) { private String replaceString(Map<String, StringBuilder> map, String sql) {
for (String key : map.keySet()) { for (Map.Entry<String, StringBuilder> key : map.entrySet()) {
sql = sql.replace(key, map.get(key).toString()); sql = sql.replace(key.getKey(), key.getValue().toString());
} }
return sql; return sql;
} }
...@@ -292,11 +312,11 @@ public class TableSqlCache { ...@@ -292,11 +312,11 @@ public class TableSqlCache {
this.table = table; this.table = table;
} }
public MemoryCache<SqlData> getSqls() { public MemoryCache<SqlData> getNameCache() {
return sqls; return nameCache;
} }
public void setSqls(MemoryCache<SqlData> sqls) { public void setNameCache(MemoryCache<SqlData> nameCache) {
this.sqls = sqls; this.nameCache = nameCache;
} }
} }
...@@ -19,121 +19,326 @@ import java.util.Map; ...@@ -19,121 +19,326 @@ import java.util.Map;
public class TableStruct { public class TableStruct {
/** /**
* 表名称 * 数据库中的表名称
*/ */
private String name; private String name;
/** /**
* 主键名称 * 缓存的字段,根据字段的类型进行缓存,同一个字段可能会属于多个类型。
*/
private Map<Integer, List<TableFieldVo>> typeFieldCache = new HashMap<>();
/**
* 构造函数
*/
public TableStruct() {
this.name = "";
}
/**
* 通过实体的字段来创建表结构信息
*
* @param name 表名称
* @param cls 关联的实体,主键放在第一位,其他字段放到后面;需要注意的是必需和表结构对应起来,会有隐性BUG,比如说在实体中增加了字段,会导致增加修改失败
*/
public TableStruct(String name, Class<?> cls) {
this.name = name;
// 获取实体中的所有字段信息,包含get、set、field
HashMap<String, MethodField> fields = ObjectHelper.getTypeField(cls);
// 遍历字段
for (Map.Entry<String, MethodField> entry : fields.entrySet()) {
// 字段信息获取
MethodField field = entry.getValue();
if (field.getField() == null && field.getGetMethod() == null) {
continue;
}
addMethodField(field);
}
}
/**
* 添加字段
*
* @param field 添加字段
*/
private void addMethodField(MethodField field) {
int fieldAction = DaoConst.FIELD_NONE;
// 默认后台数据库字段和前台参数字段为字段名,字段类型为class
String fieldName = field.getName();
String fieldInputName = field.getName();
Class<?> fieldType = String.class;
// 获取注解以及返回类型
TableAnnotation annotation = null;
if (field.getField() != null) {
annotation = field.getField().getAnnotation(TableAnnotation.class);
fieldType = field.getField().getType();
} else if (field.getGetMethod() != null) {
annotation = field.getGetMethod().getAnnotation(TableAnnotation.class);
fieldType = field.getGetMethod().getReturnType();
}
// 注解不为空,则修改后台数据库映射字段、字段类型
if (annotation != null) {
if (!StringHelper.isEmpty(annotation.value())) {
fieldName = annotation.value();
}
fieldAction = annotation.type();
}
// 将字段组合成输入字段
TableFieldVo vo = new TableFieldVo(fieldName, fieldInputName, fieldType);
// 根据字段名称规则来获取名称默认类型
int stringAction = getStringAction(vo);
// 获取普通类型字段列表
List<TableFieldVo> commonActionList = this.getFieldActionList(DaoConst.FIELD_COMMON);
// 判断是否属于主键
int resultActionType = getActionType(fieldAction, stringAction);
if (resultActionType == DaoConst.FIELD_PRIMARY) {
// 将历史主键添加到普通列,并且移除历史主键
List<TableFieldVo> primaryActionList = this.getFieldActionList(DaoConst.FIELD_PRIMARY);
commonActionList.addAll(primaryActionList);
primaryActionList.clear();
// 将现有列添加到主键
primaryActionList.add(vo);
} else {
// 将所有非主键列添加到普通列
commonActionList.add(vo);
boolean isTypeMany = resultActionType != DaoConst.FIELD_MD5
&& resultActionType != DaoConst.FIELD_REMOVE
&& resultActionType != DaoConst.FIELD_VERSION
&& resultActionType != DaoConst.FIELD_COMMON;
if (resultActionType != DaoConst.FIELD_COMMON) {
List<TableFieldVo> actionList = this.getFieldActionList(resultActionType);
// 处理其他特殊列
if (isTypeMany) {
actionList.add(vo);
} else if (resultActionType == fieldAction) {
// fieldAction 优先级高于 stringAction
// 假如特殊列已经存在,则将已经存在的特殊列删除,并且添加新的特殊列
actionList.clear();
actionList.add(vo);
} else if (actionList.isEmpty()) {
// stringAction
// 假如是默认的,并且特殊列已经存在,则不进行任何处理
actionList.add(vo);
}
}
}
}
/**
* 获取字段类型
*
* @param fieldAction 字段类型
* @param stringAction 字符串字段类型
* @return 最终类型
*/
private int getActionType(int fieldAction, int stringAction) {
if (fieldAction != DaoConst.FIELD_NONE) {
return fieldAction;
} else {
return stringAction;
}
}
/**
* 获取字符串动作类型
*
* @param vo 输入子弹
* @return 获取到的自动类型
*/ */
private TableFieldVo key; private int getStringAction(TableFieldVo vo) {
if (getKey() == null) {
return DaoConst.FIELD_PRIMARY;
} else if (DaoConst.REMOVE_FLAG.equals(vo.inputLName)) {
return DaoConst.FIELD_REMOVE;
} else if (DaoConst.VERSION_FLAG.equals(vo.inputLName)) {
return DaoConst.FIELD_VERSION;
}
// 判断是否属于统计字段
else if (DaoConst.MD5_KEY_FLAG.equals(vo.inputLName)) {
return DaoConst.FIELD_MD5;
} else if (vo.inputLName.startsWith(DaoConst.UPDATE_FLAG)) {
return DaoConst.FIELD_REMOVE_UPDATE;
} else if (vo.inputLName.startsWith(DaoConst.CREATE_FLAG)) {
return DaoConst.FIELD_CREATE;
} else {
return DaoConst.FIELD_COMMON;
}
}
/** /**
* MD5KEY * 获取某个类型的所有字段
*
* @param type 某个类型,需要排除的类型
* @param exceptType 需要排除的字段的类型
* @return 字段列表
*/ */
private TableFieldVo md5Key; private List<TableFieldVo> getFieldActionList(int type, int... exceptType) {
if (!typeFieldCache.containsKey(type)) {
typeFieldCache.put(type, new ArrayList<>());
}
List<TableFieldVo> from = typeFieldCache.get(type);
if (exceptType == null || exceptType.length == 0) {
return from;
} else {
// 缓存需要排除的子弹
Map<String, Boolean> exceptCache = new HashMap<>(10);
for (int except : exceptType) {
if (!typeFieldCache.containsKey(except)) {
continue;
}
List<TableFieldVo> exceptList = typeFieldCache.get(except);
for (TableFieldVo exceptField : exceptList) {
exceptCache.put(exceptField.name, true);
}
}
// 剩下的字段
List<TableFieldVo> to = new ArrayList<>();
for (TableFieldVo fromItem : from) {
if (exceptCache.containsKey(fromItem.name)) {
continue;
}
to.add(fromItem);
}
return to;
}
}
/** /**
* 其他字段 * 获取某个类型的第一个字段
*
* @param type 类型
* @return 获取到的子弹
*/ */
private List<TableFieldVo> fields = new ArrayList<TableFieldVo>(); private TableFieldVo getFieldAction(int type) {
List<TableFieldVo> list = getFieldActionList(type);
return !list.isEmpty() ? list.get(0) : null;
}
/**
* 获取所有普通子弹
*
* @return 所有的普通股字段
*/
public List<TableFieldVo> getFields() { public List<TableFieldVo> getFields() {
return fields; return getFieldActionList(DaoConst.FIELD_COMMON);
} }
/**
* 获取表名
*
* @return 获取到的名称
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* 设置表名
*
* @param name 设置的表名
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/**
* 主键
*
* @return 获取到的键值
*/
public TableFieldVo getKey() { public TableFieldVo getKey() {
return key; return getFieldAction(DaoConst.FIELD_PRIMARY);
}
public TableFieldVo getMd5Key() {
return md5Key;
} }
/**
* 主键名称
*
* @return 主键名称
*/
public String getKeyName() { public String getKeyName() {
return this.key.inputName; return this.getKey().inputName;
}
public String getMD5KeyName() {
return md5Key != null ? md5Key.inputName : null;
} }
/**
* 主键数据类型
*
* @return 主键类型
*/
public Class<?> getKeyType() { public Class<?> getKeyType() {
return this.key.type; return this.getKey().type;
} }
/** /**
* 构造函数 * MD5缓存字段
*
* @return md5字段
*/ */
public TableStruct() { public TableFieldVo getMd5Key() {
this.name = ""; return getFieldAction(DaoConst.FIELD_MD5);
this.key = new TableFieldVo(DaoConst.ID_FIELD);
} }
/** /**
* 通过实体的字段来创建表结构信息 * MD5缓存键值
* *
* @param name 表名称 * @return MD5名称
* @param cls 关联的实体,主键放在第一位,其他字段放到后面;需要注意的是必需和表结构对应起来,会有隐性BUG,比如说在实体中增加了字段,会导致增加修改失败
*/ */
public TableStruct(String name, Class<?> cls) { public String getMD5KeyName() {
this.name = name; TableFieldVo md5Key = this.getMd5Key();
return md5Key != null ? md5Key.inputName : null;
// 获取实体中的所有字段信息,包含get、set、field }
HashMap<String, MethodField> fields = ObjectHelper.getTypeField(cls);
// 遍历字段
for (Map.Entry<String, MethodField> entry : fields.entrySet()) {
// 字段信息获取 /**
MethodField field = entry.getValue(); * 判断是否包含版本号字段
if (field.field == null && field.getMethod == null) { *
continue; * @return 版本号字段
} */
public TableFieldVo getVersion() {
return getFieldAction(DaoConst.FIELD_VERSION);
}
String fieldName = field.name; /**
String fieldInputName = field.name; * 判断是否包含remove字段
Class<?> fieldType = String.class; *
TableAnnotation annotation = null; * @return 删除字段
if (field.field != null) { */
annotation = field.field.getAnnotation(TableAnnotation.class); public TableFieldVo getRemove() {
fieldType = field.field.getType(); return getFieldAction(DaoConst.FIELD_REMOVE);
} else if (field.getMethod != null) { }
annotation = field.getMethod.getAnnotation(TableAnnotation.class);
fieldType = field.getMethod.getReturnType();
}
if (annotation != null) {
fieldName = annotation.value();
}
TableFieldVo vo = new TableFieldVo(fieldName, fieldInputName, fieldType);
// 判断是否属于统计字段
if ("md5key".equals(vo.inputLName)) {
this.md5Key = vo;
}
// 判断是否是主键,获取主键数据类型 /**
if (this.key == null) { * 获取删除时更新子弹
this.key = vo; *
} else { * @return 删除时更新字段
this.fields.add(vo); */
} public List<TableFieldVo> getRemoveUpdate() {
} return getFieldActionList(DaoConst.FIELD_REMOVE_UPDATE);
} }
/**
* 获取某一列
*
* @param name 列名
* @return 获取到的字段
*/
public TableFieldVo getField(String name) { public TableFieldVo getField(String name) {
if (StringHelper.isEmpty(name)) { if (StringHelper.isEmpty(name)) {
return null; return null;
} }
for (TableFieldVo fieldVo : this.fields) { for (TableFieldVo fieldVo : this.getFields()) {
if (fieldVo.lName.equals(name.toLowerCase()) || fieldVo.inputLName.equals(name.toLowerCase())) { if (fieldVo.lName.equals(name.toLowerCase()) || fieldVo.inputLName.equals(name.toLowerCase())) {
return fieldVo; return fieldVo;
} }
...@@ -142,52 +347,71 @@ public class TableStruct { ...@@ -142,52 +347,71 @@ public class TableStruct {
} }
/** /**
* 判断是否包含版本号字段 * 通过表结构自动生成SQL语句
* *
* @return * @return 初始化的表SQL语句
*/ */
public TableFieldVo getVersion() { public void init(TableSqlCache table) {
return this.getField(DaoConst.VERSON); table.setTable(this);
if (!StringHelper.isEmpty(this.name)) {
table.add(releaseSqlCreate(), releaseSqlUpdate(), releaseSqlRemove(), releaseSqlLoad());
}
initSaveWith(table);
initAddGroup(table);
} }
/** /**
* 判断是否包含remove字段 * 初始化SaveWith
* *
* @return * @return 初始化的表SQL语句
*/ */
private TableFieldVo getRemove() { private void initSaveWith(TableSqlCache table) {
return this.getField(DaoConst.ISREMOVE); List<TableFieldVo> saveWithField = getFieldActionList(DaoConst.FIELD_SAVE_WITH);
if (saveWithField == null || saveWithField.isEmpty()) {
return;
}
this.addSaveWithSql(table, DaoConst.SAVE_WITH, saveWithField);
} }
/** /**
* 通过表结构自动生成SQL语句 * 初始化添加统计SQL语句
* *
* @return * @return 初始化的表SQL语句
*/ */
public void init(TableSqlCache table) { private void initAddGroup(TableSqlCache table) {
table.setTable(this); List<TableFieldVo> addGroupField = getFieldActionList(DaoConst.FIELD_ADD_GROUP);
if (!StringHelper.isEmpty(this.name)) { if (addGroupField == null || addGroupField.isEmpty()) {
table.add(releaseSqlCreate(), releaseSqlUpdate(), releaseSqlRemove(), releaseSqlLoad()); return;
} }
List<TableFieldVo> commonField = getFieldActionList(DaoConst.FIELD_COMMON,
DaoConst.FIELD_ADD_GROUP, DaoConst.FIELD_MD5,
DaoConst.FIELD_REMOVE, DaoConst.FIELD_REMOVE_UPDATE, DaoConst.FIELD_CREATE);
this.addGroupSql(table, commonField, addGroupField);
} }
/** /**
* 生成创建的SQL语句 * 生成创建的SQL语句
* *
* @return * @return 生成的语句
*/ */
private SqlData releaseSqlCreate() { private SqlData releaseSqlCreate() {
// 生成添加的SQL语句 // 生成添加的SQL语句
String text = DaoConst.INSERT_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_INSERT.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(DaoConst.CREATE, text); SqlData sql = new SqlData(DaoConst.CREATE, text);
String flag = ""; sql.setSqlType(DaoConst.SQL_TYPE_CREATE);
// 第一个增加的字段,不需要增加 ","
String flag = StringHelper.EMPTY;
if (this.getKeyType() == String.class) { if (this.getKeyType() == String.class) {
sql.addParaConst(this.key.inputName, DaoConst.FIELD_CODE, this.key.name, DaoConst.VALUES_CODE, "?"); sql.addParaConst(this.getKey().inputName, DaoConst.CODE_FIELD, this.getKey().name,
flag = ","; DaoConst.CODE_VALUES, DaoConst.CODE_PARA
);
flag = DaoConst.CODE_SPLIT;
} }
for (TableFieldVo field : this.fields) { for (TableFieldVo field : this.getFields()) {
sql.addParaConst(field.inputName, DaoConst.FIELD_CODE, flag + field.name, DaoConst.VALUES_CODE, flag + "?"); sql.addParaConst(field.inputName, DaoConst.CODE_FIELD, flag + field.name,
flag = ","; DaoConst.CODE_VALUES, flag + DaoConst.CODE_PARA
);
flag = DaoConst.CODE_SPLIT;
} }
return sql; return sql;
} }
...@@ -195,30 +419,32 @@ public class TableStruct { ...@@ -195,30 +419,32 @@ public class TableStruct {
/** /**
* 生成修改的SQL语句 * 生成修改的SQL语句
* *
* @return * @return 生成的语句
*/ */
private SqlData releaseSqlUpdate() { private SqlData releaseSqlUpdate() {
// 生成添加的SQL语句 // 生成添加的SQL语句
String text = DaoConst.UPDATE_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_UPDATE.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(DaoConst.UPDATE, text); SqlData sql = new SqlData(DaoConst.UPDATE, text);
TableFieldVo removeField = this.getRemove(); sql.setSqlType(DaoConst.SQL_TYPE_UPDATE);
TableFieldVo versionField = this.getVersion();
sql.addParaConst(this.key.inputName, // 主键字段操作
DaoConst.FIELD_CODE, "" + this.key.name + "=" + this.key.name, sql.addCode(DaoConst.CODE_FIELD, String.format(DaoConst.CODE_UPDATE_PRIMARY, this.getKey().name, this.getKey().name));
DaoConst.WHERE_CODE, " AND " + this.key.name + "=?"); sql.addConst(this.getKey().inputName, String.format(DaoConst.CODE_WHERE_EQUALS_PARA, this.getKey().name));
for (TableFieldVo field : this.fields) {
if (field == removeField || field == versionField) { // 增加普通代码片段字段
continue; List<TableFieldVo> updateList = getFieldActionList(DaoConst.FIELD_COMMON,
} DaoConst.FIELD_CREATE, DaoConst.FIELD_REMOVE, DaoConst.FIELD_VERSION);
sql.addParaConst(field.inputName, DaoConst.FIELD_CODE, "," + field.name + "=?"); for (TableFieldVo field : updateList) {
sql.addParaConst(field.inputName,
DaoConst.CODE_FIELD, String.format(DaoConst.CODE_UPDATE_FIELD_PARA, field.name)
);
} }
if (removeField != null) { // 添加删除字段
sql.addParaConst(removeField.inputName, DaoConst.WHERE_CODE, " AND " + removeField.name + "=0"); addWhereRemove(sql);
} addUpdateVersion(sql);
if (versionField != null) { // 添加版本号条件
sql.addParaConst(versionField.inputName, if (getVersion() != null) {
DaoConst.FIELD_CODE, "," + versionField.name + "=1+" + versionField.name, sql.addConst(getVersion().inputName, String.format(DaoConst.CODE_WHERE_EQUALS_PARA, getVersion().name));
DaoConst.WHERE_CODE, " AND " + versionField.name + "=?");
} }
return sql; return sql;
} }
...@@ -226,25 +452,34 @@ public class TableStruct { ...@@ -226,25 +452,34 @@ public class TableStruct {
/** /**
* 生成删除的SQL语句 * 生成删除的SQL语句
* *
* @return * @return 生成的语句
*/ */
private SqlData releaseSqlRemove() { private SqlData releaseSqlRemove() {
TableFieldVo removeField = this.getRemove(); if (this.getRemove() != null) {
TableFieldVo versionField = this.getVersion();
if (removeField != null) {
// 生成添加的SQL语句 // 生成添加的SQL语句
String text = DaoConst.UPDATE_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_UPDATE.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(DaoConst.REMOVE, text); SqlData sql = new SqlData(DaoConst.REMOVE, text);
sql.addCode(DaoConst.FIELD_CODE, removeField.name + "=1"); sql.setSqlType(DaoConst.SQL_TYPE_REMOVE);
if (versionField != null) {
sql.addCode(DaoConst.FIELD_CODE, "," + versionField.name + "=1+" + versionField.name); // 设置删除字段标记
sql.addCode(DaoConst.CODE_FIELD, String.format(DaoConst.CODE_UPDATE_FIELD_REMOVE, this.getRemove().name));
// 设置删除时需要修改的字段的值
for (TableFieldVo field : this.getFieldActionList(DaoConst.FIELD_REMOVE_UPDATE)) {
sql.addParaConst(field.inputName,
DaoConst.CODE_FIELD, String.format(DaoConst.CODE_UPDATE_FIELD_PARA, field.name)
);
} }
addWhereField(sql, ""); // 增加版本号字段的值
addUpdateVersion(sql);
// 生成逻辑删除WHERE条件
addWhereField(sql, DaoConst.CODE_TAG, true);
return sql; return sql;
} else { } else {
String text = DaoConst.REMOVE_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_REMOVE.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(DaoConst.REMOVE, text); SqlData sql = new SqlData(DaoConst.REMOVE, text);
addWhereField(sql, ""); // 生成删除语句Where条件
addWhereField(sql, DaoConst.CODE_TAG, true);
return sql; return sql;
} }
} }
...@@ -252,125 +487,191 @@ public class TableStruct { ...@@ -252,125 +487,191 @@ public class TableStruct {
/** /**
* 生成加载的SQL语句 * 生成加载的SQL语句
* *
* @return * @return 生成的语句
*/ */
private SqlData releaseSqlLoad() { private SqlData releaseSqlLoad() {
// 生成添加的SQL语句 // 生成添加的SQL语句
String text = DaoConst.LOAD_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_LOAD.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(DaoConst.LOAD, text); SqlData sql = new SqlData(DaoConst.LOAD, text);
addWhereField(sql, "a."); sql.setSqlType(DaoConst.SQL_TYPE_LOAD);
// 生成加载语句的WHERE条件
addWhereField(sql, DaoConst.CODE_TAG, false);
return sql; return sql;
} }
/** /**
* 当前当前表所有字段的等于SQL语句 * 当前当前表所有字段的等于SQL语句
* *
* @param sql * @param sql SDL语句
* @param tag 标记
* @param isRemove 是否生成删除相关字段
* @return 生成的语句
*/ */
private void addWhereField(SqlData sql, String tag) { private void addWhereField(SqlData sql, String tag, boolean isRemove) {
TableFieldVo removeField = this.getRemove(); sql.add(this.getKey().inputName,
sql.add(this.key.inputName, " AND " + tag + this.key.name + "=?"); String.format(DaoConst.CODE_WHERE_EQUALS, tag, this.getKey().name, DaoConst.CODE_PARA)
for (TableFieldVo field : this.fields) { );
sql.add(field.inputName, " AND " + tag + field.name + "=?");
// Where条件包含的字段
List<TableFieldVo> fields;
if (!isRemove) {
// 所有字段
fields = this.getFields();
} else {
// 非删除时需要更新的字段
fields = this.getFieldActionList(DaoConst.FIELD_COMMON, DaoConst.FIELD_REMOVE_UPDATE);
} }
if (removeField != null) { // 添加普通的Where条件
sql.addConst(DaoConst.ISREMOVE_CONTANS, " AND " + tag + removeField.name + "=0"); for (TableFieldVo field : fields) {
sql.add(field.inputName,
String.format(DaoConst.CODE_WHERE_EQUALS, tag, field.name, DaoConst.CODE_PARA)
);
} }
// 查询时,不能查询到非删除的字段
addWhereRemove(sql);
} }
/** /**
* 生成统计的SQL语句 * 添加删除WHERE条件字段
* *
* @param sqlTableData 需要生成的实体 * @param sql SQL语句实体
* @param whereFields WHERE字段
* @param updateFields 需要增加的值的字段
*/ */
public void addGroupSql(TableSqlCache sqlTableData, TableFieldString whereFields, TableFieldString updateFields) { private void addWhereRemove(SqlData sql) {
sqlTableData.add(this.releaseSqlWhere(DaoConst.GROUP_QUERY, DaoConst.LOAD_MODEL, whereFields)); if (getRemove() != null) {
sqlTableData.add(this.releaseSql(DaoConst.GROUP_ADD, DaoConst.UPDATE_MODEL, "{FIELD}={FIELD}+?", updateFields, new TableFieldString(this.key.name))); sql.addParaConst(DaoConst.REMOVE_FLAG_INPUT,
DaoConst.CODE_WHERE,
String.format(DaoConst.CODE_WHERE_EQUALS_NOT_REMOVE, this.getRemove().name)
);
}
} }
/** /**
* 生成SQL语句 * 版本号进行累加
* *
* @param name * @param sql 需要处理的SQL语句
* @param model
* @param whereFields
* @return
*/ */
public SqlData releaseSqlWhere(String name, String model, TableFieldString whereFields) { private void addUpdateVersion(SqlData sql) {
return this.releaseSql(name, model, "", new TableFieldString(), whereFields); // 添加版本字段
if (getVersion() != null) {
sql.addCode(DaoConst.CODE_FIELD, String.format(DaoConst.CODE_UPDATE_VERSION_FIELD, getVersion().name, getVersion().name));
}
} }
/** /**
* 生成SQL语句 * 生成SQL语句
* *
* @param sqlType SQL语句类型
* @param name SQL语句名称 * @param name SQL语句名称
* @param model SQL语句模板 * @param model SQL语句模板
* @param valueModel 值字段模板 * @param valueModel 值字段模板
* @param valueFields 值字段 * @param valueFields 值字段
* @param whereFields WHERE字段 * @param whereFields WHERE字段
* @return * @return 生成的SQL语句
*/ */
public SqlData releaseSql(String name, String model, String valueModel, TableFieldString valueFields, TableFieldString whereFields) { private SqlData releaseSql(int sqlType, String name, String model, String valueModel, List<TableFieldVo> valueFields, List<TableFieldVo> whereFields) {
// 参数字段 // 参数字段
List<String> paraFields = new ArrayList<String>(); List<String> paraFields = new ArrayList<String>();
// 生成修改的SQL语句
SqlData sql = new SqlData(name, model.replace(DaoConst.CODE_TABLE, this.name));
sql.setSqlType(sqlType);
// 生成添加的SQL语句 // 生成添加的SQL语句
StringBuilder sbField = new StringBuilder(); String flag = StringHelper.EMPTY;
for (String field : valueFields.getFields()) { for (TableFieldVo field : valueFields) {
if (sbField.length() > 0) { sql.addParaConst(field.inputName, DaoConst.CODE_FIELD, flag + valueModel.replace(DaoConst.CODE_FIELD, field.name));
sbField.append(","); flag = DaoConst.CODE_SPLIT;
}
sbField.append(valueModel.replace(DaoConst.FIELD_CODE, field));
paraFields.add(field);
} }
StringBuilder sbWhere = new StringBuilder(); for (TableFieldVo field : whereFields) {
for (String field : whereFields.getFields()) { sql.addParaConst(field.inputName, DaoConst.CODE_WHERE, String.format(DaoConst.CODE_WHERE_EQUALS_PARA, field.name));
sbWhere.append(" AND ");
sbWhere.append(field);
sbWhere.append("=?");
paraFields.add(field);
} }
String[] fields = new String[paraFields.size()]; return sql;
fields = paraFields.toArray(fields); }
// 生成修改的SQL语句
String sql = model.replace(DaoConst.TABLE_CODE, this.name).replace(DaoConst.FIELD_CODE, sbField.toString()).replace(DaoConst.WHERE_CODE, sbWhere.toString()); /**
SqlData ret = new SqlData(name, sql, fields); * 根据来源字符串获取结束字符串
return ret; *
* @param fieldFrom 来源字符串
* @return 返回字符串
*/
private List<TableFieldVo> getFieldString(TableFieldString fieldFrom) {
List<TableFieldVo> list = new ArrayList<>();
for (String fieldName : fieldFrom.getFields()) {
list.add(this.getField(fieldName));
}
return list;
} }
/** /**
* 生成根据某些字段不存在则保存的SQL语句 * 生成根据某些字段不存在则保存的SQL语句
* *
* @param tableStruct * @param tableStruct 表结构
* @param sqlName * @param sqlName SQL语句
* @param whereFields * @param whereFields WHERE条件
*/ */
public void addSaveWithSql(TableSqlCache tableStruct, String sqlName, TableFieldString whereFields) { public void addSaveWithSql(TableSqlCache tableStruct, String sqlName, TableFieldString whereFields) {
tableStruct.add(this.releaseSqlWhere(sqlName, DaoConst.LOAD_MODEL, whereFields)); addSaveWithSql(tableStruct, sqlName, getFieldString(whereFields));
} }
/**
* 生成根据某些字段不存在则保存的SQL语句
*
* @param tableStruct 表结构
* @param sqlName SQL语句
* @param whereFields WHERE条件
*/
private void addSaveWithSql(TableSqlCache tableStruct, String sqlName, List<TableFieldVo> whereFields) {
SqlData sqlData = this.releaseSql(DaoConst.SQL_TYPE_SAVE_WITH, sqlName, DaoConst.SQL_LOAD, StringHelper.EMPTY, new ArrayList<>(), whereFields);
tableStruct.add(sqlData);
}
/**
* 生成统计的SQL语句
*
* @param sqlTableData 需要生成的实体
* @param whereFields WHERE字段
* @param updateFields 需要增加的值的字段
*/
public void addGroupSql(TableSqlCache sqlTableData, TableFieldString whereFields, TableFieldString updateFields) {
addGroupSql(sqlTableData, getFieldString(whereFields), getFieldString(updateFields));
}
/**
* 生成统计的SQL语句
*
* @param sqlTableData 需要生成的实体
* @param whereFields WHERE字段
* @param updateFields 需要增加的值的字段
*/
private void addGroupSql(TableSqlCache sqlTableData, List<TableFieldVo> whereFields, List<TableFieldVo> updateFields) {
sqlTableData.add(this.releaseSql(DaoConst.SQL_TYPE_ADD_GROUP, DaoConst.GROUP_QUERY, DaoConst.SQL_LOAD,
StringHelper.EMPTY, new ArrayList<>(), whereFields));
sqlTableData.add(this.releaseSql(DaoConst.SQL_TYPE_ADD_GROUP, DaoConst.GROUP_ADD, DaoConst.SQL_UPDATE,
DaoConst.CODE_GROUP_ADD, updateFields, this.getFieldActionList(DaoConst.FIELD_PRIMARY)));
}
/** /**
* 生成判断数据是否存在的SQL语句 * 生成判断数据是否存在的SQL语句
* *
* @param sqlTableData * @param sqlTableData 表结构
* @param sqlName * @param sqlName SQL语句的名称
* @param fields * @param fields 需要判断的字段
*/ */
public void addExist(TableSqlCache sqlTableData, String sqlName, String[] fields) { public void addExist(TableSqlCache sqlTableData, String sqlName, String[] fields) {
String text = DaoConst.LOAD_MODEL.replace(DaoConst.TABLE_CODE, this.name); String text = DaoConst.SQL_LOAD.replace(DaoConst.CODE_TABLE, this.name);
SqlData sql = new SqlData(sqlName, text); SqlData sql = new SqlData(sqlName, text);
sql.addPara(this.key.inputName, DaoConst.WHERE_CODE, " AND a." + this.key.name + "<>?"); sql.setSqlType(DaoConst.SQL_TYPE_SAVE_WITH);
for (String field : fields) { sql.addConst(this.getKey().inputName,
sql.addParaConst(field, DaoConst.WHERE_CODE, " AND a." + field + "=?"); String.format(DaoConst.CODE_WHERE_NOT_EQUALS_PARA, this.getKey().name)
} );
if (getRemove() != null) {
sql.addParaConst(DaoConst.ISREMOVE_CONTANS, DaoConst.WHERE_CODE, " AND a." + DaoConst.ISREMOVE + "=0"); for (String fieldName : fields) {
TableFieldVo field = this.getField(fieldName);
sql.addConst(field.inputName,
String.format(DaoConst.CODE_WHERE_EQUALS_PARA, field.name)
);
} }
addWhereRemove(sql);
sqlTableData.add(sql); sqlTableData.add(sql);
} }
} }
package com.yanzuoguang.db.impl; package com.yanzuoguang.db.impl;
import com.yanzuoguang.dao.DaoConst; import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.TableAnnotation;
import com.yanzuoguang.extend.ConfigDb; import com.yanzuoguang.extend.ConfigDb;
import com.yanzuoguang.util.base.MethodField;
import com.yanzuoguang.util.base.ObjectHelper; import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log; import com.yanzuoguang.util.log.Log;
...@@ -13,9 +15,6 @@ import org.springframework.jdbc.support.JdbcUtils; ...@@ -13,9 +15,6 @@ import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
...@@ -25,6 +24,7 @@ import java.util.Map; ...@@ -25,6 +24,7 @@ import java.util.Map;
/** /**
* 将数据映射为结果 * 将数据映射为结果
*
* @author 颜佐光 * @author 颜佐光
*/ */
public class AllBeanRowMapper<T> implements RowMapper<T> { public class AllBeanRowMapper<T> implements RowMapper<T> {
...@@ -35,24 +35,14 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -35,24 +35,14 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
private Class<T> mappedClass; private Class<T> mappedClass;
/** /**
* Mappings是否属于字段s * 是否属于映射方式
*/
private Map<String, Boolean> mappedIsFields;
/**
* 需要映射的字段
*/
private Map<String, Field> mappedFields;
/**
* 需要映射的属性
*/ */
private Map<String, PropertyDescriptor> mappedPropertys; private boolean isMapping = false;
/** /**
* 是否属于映射方式 * 获取字段映射关系
*/ */
private boolean isMapping = false; private Map<String, MethodField> typeField;
/** /**
* 配置信息 * 配置信息
...@@ -76,32 +66,29 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -76,32 +66,29 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/ */
protected void initialize(Class<T> mappedClass) { protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass; this.mappedClass = mappedClass;
this.mappedFields = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
this.mappedPropertys = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
this.mappedIsFields = new HashMap<>(DaoConst.COLLECTION_INIT_SIZE);
if (ObjectHelper.isSub(MapRow.class, mappedClass) || ObjectHelper.isSub(Map.class, mappedClass)) { if (ObjectHelper.isSub(MapRow.class, mappedClass) || ObjectHelper.isSub(Map.class, mappedClass)) {
isMapping = true; isMapping = true;
} else { } else {
Field[] fields = mappedClass.getFields(); Map<String, MethodField> temp = ObjectHelper.getTypeField(mappedClass);
for (Field item : fields) { typeField = new HashMap<>(temp.size());
if (Modifier.isStatic(item.getModifiers())) {
continue; for (Map.Entry<String, MethodField> item : temp.entrySet()) {
String name = item.getKey();
// 获取字段值
MethodField field = item.getValue();
// 获取名称
TableAnnotation annotation = null;
if (field.getField() != null) {
annotation = field.getField().getAnnotation(TableAnnotation.class);
} else if (field.getGetMethod() != null) {
annotation = field.getGetMethod().getAnnotation(TableAnnotation.class);
} }
String name = item.getName(); if (annotation != null && !StringHelper.isEmpty(annotation.value())) {
String underscoredName = underscoreName(name); name = annotation.value();
this.mappedFields.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, true);
}
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor item : pds) {
if (item.getWriteMethod() != null) {
String name = item.getName();
String underscoredName = underscoreName(name);
this.mappedPropertys.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, false);
} }
String underscoredName = underscoreName(name);
this.typeField.put(underscoredName, item.getValue());
} }
} }
} }
...@@ -138,8 +125,8 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -138,8 +125,8 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/ */
public static MapRow toLoweRow(MapRow from) { public static MapRow toLoweRow(MapRow from) {
MapRow to = new MapRow(); MapRow to = new MapRow();
for (String key : from.keySet()) { for (Map.Entry<String, Object> key : from.entrySet()) {
to.put(underscoreNameBase(key), from.get(key)); to.put(underscoreNameBase(key.getKey()), key.getValue());
} }
return to; return to;
} }
...@@ -152,9 +139,9 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -152,9 +139,9 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/ */
public static Object getLoweRowField(MapRow from, String field) { public static Object getLoweRowField(MapRow from, String field) {
field = underscoreNameBase(field); field = underscoreNameBase(field);
for (String key : from.keySet()) { for (Map.Entry<String, Object> key : from.entrySet()) {
if (underscoreNameBase(key).equals(field)) { if (underscoreNameBase(key.getKey()).equals(field)) {
return from.get(key); return key.getValue();
} }
} }
return null; return null;
...@@ -170,8 +157,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -170,8 +157,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
public T mapRow(ResultSet rs, int rowNumber) throws SQLException, TypeMismatchException { public T mapRow(ResultSet rs, int rowNumber) throws SQLException, TypeMismatchException {
Assert.state(this.mappedClass != null, "Mapped class was not specified"); Assert.state(this.mappedClass != null, "Mapped class was not specified");
T mappedObject = BeanUtils.instantiate(this.mappedClass); T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
ResultSetMetaData rsmd = rs.getMetaData(); ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount(); int columnCount = rsmd.getColumnCount();
...@@ -185,53 +170,36 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -185,53 +170,36 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
value = JdbcUtils.getResultSetValue(rs, index, String.class); value = JdbcUtils.getResultSetValue(rs, index, String.class);
} }
((Map) mappedObject).put(getCamelCase(column), value); ((Map) mappedObject).put(getCamelCase(column), value);
} else if (!this.mappedIsFields.containsKey(underscoredName)) { } else if (!this.typeField.containsKey(underscoredName)) {
continue; continue;
} else if (!this.mappedIsFields.get(underscoredName)) {
PropertyDescriptor pd = this.mappedPropertys.get(underscoredName);
Class<?> type = pd.getPropertyType();
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException e) {
if (value == null) {
Log.info(AllBeanRowMapper.class,
"Intercepted TypeMismatchException for row %d and column '%s' with " +
"value %s when setting property '%s' of type %s on object: %s",
rowNumber, column, value, pd.getName(), type, mappedObject);
} else {
throw e;
}
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex);
}
} else { } else {
Field pd = this.mappedFields.get(underscoredName); MethodField pd = this.typeField.get(underscoredName);
Class<?> type = pd.getType(); Class<?> type;
if (pd.getField() != null) {
type = pd.getField().getType();
} else {
type = pd.getGetMethod().getReturnType();
}
Object value = null;
try { try {
Object value = JdbcUtils.getResultSetValue(rs, index, type); value = JdbcUtils.getResultSetValue(rs, index, type);
if (configDb.isPrintMapper() && rowNumber == 0) { if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type); Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
} }
try { ObjectHelper.setByType(mappedObject, pd, value);
pd.set(mappedObject, value); } catch (TypeMismatchException e) {
} catch (IllegalAccessException e) { if (value == null) {
if (value == null) { Log.info(AllBeanRowMapper.class,
Log.info(AllBeanRowMapper.class, "Intercepted TypeMismatchException for row %d and column '%s' with " +
"Intercepted TypeMismatchException for row %d and column '%s' with " + "value %s when setting property '%s' of type %s on object: %s",
"value %s when setting property '%s' of type %s on object: %s", rowNumber, column, StringHelper.EMPTY, pd.getName(), type, mappedObject);
rowNumber, column, value, pd.getName(), type, mappedObject); } else {
} else { throw e;
throw e;
}
} }
} catch (IllegalAccessException ex) { } catch (Exception ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to field " + pd.getName(), ex); throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex);
} }
} }
} }
...@@ -257,17 +225,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> { ...@@ -257,17 +225,6 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
return column; return column;
} }
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
*
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/** /**
* 缓存的处理类 * 缓存的处理类
*/ */
......
...@@ -336,7 +336,10 @@ public class ExcelConsole<T extends Object> implements DbRow<T> { ...@@ -336,7 +336,10 @@ public class ExcelConsole<T extends Object> implements DbRow<T> {
workbook = null; workbook = null;
} }
File file = new File(this.getFileName()); File file = new File(this.getFileName());
if (file.exists() && file.delete()) { if (file.exists()) {
if (!file.delete()) {
throw new CodeException("文件删除失败");
}
} }
return this; return this;
} }
......
...@@ -49,7 +49,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> { ...@@ -49,7 +49,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/ */
@Override @Override
public List<String> create(T... models) { public List<String> create(T... models) {
List<String> ids = new ArrayList<String>(); List<String> ids = new ArrayList<>();
for (T t : models) { for (T t : models) {
String id = createItem(t); String id = createItem(t);
ids.add(id); ids.add(id);
...@@ -76,7 +76,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> { ...@@ -76,7 +76,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/ */
@Override @Override
public List<String> update(T... models) { public List<String> update(T... models) {
List<String> ids = new ArrayList<String>(); List<String> ids = new ArrayList<>();
for (T t : models) { for (T t : models) {
String id = updateItem(t); String id = updateItem(t);
ids.add(id); ids.add(id);
...@@ -103,7 +103,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> { ...@@ -103,7 +103,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/ */
@Override @Override
public List<String> save(T... models) { public List<String> save(T... models) {
List<String> ids = new ArrayList<String>(); List<String> ids = new ArrayList<>();
for (T item : models) { for (T item : models) {
String id = saveItem(item); String id = saveItem(item);
ids.add(id); ids.add(id);
...@@ -157,7 +157,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> { ...@@ -157,7 +157,7 @@ public abstract class BaseServiceImpl<T> implements BaseService<T> {
*/ */
@Override @Override
public List<T> load(T... models) { public List<T> load(T... models) {
List<T> tos = new ArrayList<T>(); List<T> tos = new ArrayList<>();
for (T item : models) { for (T item : models) {
T to = loadItem(item); T to = loadItem(item);
tos.add(to); tos.add(to);
......
...@@ -40,7 +40,7 @@ public class TokenHelper { ...@@ -40,7 +40,7 @@ public class TokenHelper {
/** /**
* 内存缓存 * 内存缓存
*/ */
protected static MemoryCache<TokenData> cache = new MemoryCache<>(); protected final static MemoryCache<TokenData> cache = new MemoryCache<>();
/** /**
......
package com.yanzuoguang.token; package com.yanzuoguang.token;
import com.yanzuoguang.util.vo.MapRow;
/** /**
* 动态加载Token * 动态加载Token
* *
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment