Commit 3212f487 authored by yanzg's avatar yanzg

打印日志

parent c5d2b285
......@@ -51,12 +51,17 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
*/
private boolean isMapping = false;
/**
* 配置信息
*/
private ConfigDb configDb;
/**
* 构造函数
*
* @param mappedClass
*/
public AllBeanRowMapper(Class<T> mappedClass) {
public AllBeanRowMapper(Class<T> mappedClass, ConfigDb configDb) {
initialize(mappedClass);
}
......@@ -140,7 +145,7 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
Class<?> type = pd.getPropertyType();
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
if (ConfigDb.PrintMapper && rowNumber == 0) {
if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
......@@ -165,7 +170,7 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
// value = StringHelper.get(type,value);
if (ConfigDb.PrintMapper && rowNumber == 0) {
if (configDb.isPrintMapper() && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
......@@ -212,9 +217,9 @@ public class AllBeanRowMapper<T> implements RowMapper<T> {
* @param <T> 泛型类型
* @return 可转换的实体
*/
public static <T extends Object> AllBeanRowMapper<T> getIntance(Class<T> cls) {
public static <T extends Object> AllBeanRowMapper<T> getInstance(Class<T> cls, ConfigDb configDb) {
if (!Cache.containsKey(cls)) {
Cache.put(cls, new AllBeanRowMapper<T>(cls));
Cache.put(cls, new AllBeanRowMapper<T>(cls, configDb));
}
AllBeanRowMapper<T> ret = (AllBeanRowMapper<T>) Cache.get(cls);
return ret;
......
package com.yanzuoguang.db.Impl;
import com.yanzuoguang.db.DbExecute;
import com.yanzuoguang.extend.ConfigDb;
import com.yanzuoguang.util.vo.MapRow;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
......@@ -24,6 +25,9 @@ public class DbExecuteImpl implements DbExecute {
@Resource
private DbPrintSql printSql;
@Resource
private ConfigDb configDb;
/**
* 更新SQL语句的执行
*
......@@ -55,7 +59,7 @@ public class DbExecuteImpl implements DbExecute {
int row = 0;
try {
sql = this.handleParas(sql, paras);
List<T> ret = jdbc.query(sql, paras, AllBeanRowMapper.getIntance(cls));
List<T> ret = jdbc.query(sql, paras, AllBeanRowMapper.getInstance(cls, configDb));
if (ret == null) {
ret = new ArrayList<T>();
}
......
......@@ -5,9 +5,14 @@ import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class DbPrintSql {
@Resource
private ConfigDb configDb;
/**
* 打印SQL语句
*
......@@ -16,11 +21,11 @@ public class DbPrintSql {
*/
public void print(int row, String sql, Object... paras) {
// 日志表忽略打印
if (!ConfigDb.PrintSql) {
if (!configDb.isPrintSql()) {
return;
}
if (!StringHelper.isEmpty(ConfigDb.PrintSqlFilter)) {
if (sql.matches(ConfigDb.PrintSqlFilter)) {
if (!StringHelper.isEmpty(configDb.getPrintSqlFilter())) {
if (sql.matches(configDb.getPrintSqlFilter())) {
return;
}
}
......@@ -38,7 +43,7 @@ public class DbPrintSql {
sql = sql.replaceFirst("\\?", "'" + str.replace("'", "''") + "'");
}
}
Log.infoTag(DbExecuteImpl.class, String.format("%d row", row), sql);
Log.infoTag(DbPrintSql.class, String.format("%d row", row), sql);
}
}
package com.yanzuoguang.db.db.code;
/**
* 加密算法生成接口
*/
public interface CodePwd {
/**
* 获取算法的名称
*
* @return
*/
String getName();
/**
* 生成二维码
*
* @param rand 随机数
* @param day 日期
* @param index 序号
* @param pwd 密码
* @return 生成的结果
*/
String getCode(String rand, String day, String index, String pwd);
}
package com.yanzuoguang.db.db.code;
/**
* 加密算法0版实现
*/
public class CodePwdImpl implements CodePwd {
/**
* 当前算法的名称
*
* @return
*/
@Override
public String getName() {
/**
* 颜佐光的第一个版本的算法
*/
return "Yanzuoguang.Zero";
}
/**
* 生成二维码
*
* @param rand 随机数
* @param day 日期
* @param index 序号
* @param pwd 密码
* @return 生成的结果
*/
@Override
public String getCode(String rand, String day, String index, String pwd) {
String ret = "";
// 1. 将随即数和天数进行组合生成字符串
String randDay = "";
{
int randSize = rand.length();
int daySize = day.length();
int maxLen = Math.max(rand.length(), day.length());
for (int i = 0; i < maxLen; i++) {
if (i < daySize) {
randDay += day.charAt(i);
}
if (i < randSize) {
randDay += rand.charAt(i);
}
}
}
// 2. 将组合后的数字进行交换
int randDaySize = randDay.length();
char[] dayChars = new char[randDaySize];
{
for (int i = 0; i < randDaySize; i++) {
dayChars[i] = randDay.charAt(i);
}
for (int i = 0; i < randDaySize / 2; i++) {
if (i % 2 == 0) {
int to = randDaySize - i - 1;
dayChars[to] = randDay.charAt(i);
dayChars[i] = randDay.charAt(to);
}
}
for (int i = 0; i < randDaySize; i++) {
ret += dayChars[i];
}
}
// 3.a 将随机数和后面的序号组成新的字符串
String codePwd = index;
// 3.b 将新的字符串加上密码进行处理
int newSize = codePwd.length();
int pwdSize = pwd.length();
int[] newValue = new int[newSize];
// 3.c 转换为具体的数字,并且加上密码
for (int i = 0; i < newSize; i++) {
int from = Integer.parseInt("" + codePwd.charAt(i));
int pwdIndex = i % pwdSize;
int to = Integer.parseInt("" + pwd.charAt(pwdIndex));
int val = (from + to);
newValue[i] = val;
}
// 根据最后一位数字进行相加
int last = newValue[newSize - 1];
for (int i = 0; i < newSize - 1; i++) {
int flag = 1;
if (last % 2 == 0) {
flag = -flag;
}
if (newValue[i] % 2 == 0) {
flag = -flag;
}
if (i % 2 == 0) {
flag = -flag;
}
newValue[i] += flag * last;
}
// 往后移动5位
int movePos = newSize / 2;
int[] toVals = new int[newSize];
for (int i = 0; i < newSize; i++) {
int j = i - movePos;
if (j < 0) {
j = newSize + j;
}
toVals[i] = newValue[j];
}
newValue = toVals;
for (int i = 0; i < newSize; i++) {
newValue[i] = (newValue[i] % 10 + 10) % 10;
ret += newValue[i];
}
return ret;
}
// public static void main(String[] args) {
// int[] pos2 = {3, 4, 5, 6, 8};
// int startPos = 0;
// int endPos = 1000000;
//
// Date start = new Date();
// CodePwdReplaceImpl item = new CodePwdReplaceImpl();
// Map<String, Integer> map = new HashMap<>();
// for (int i = startPos; i < endPos; i++) {
// String index = String.format("%09d", i);
// String code = item.getCode("", "", index, "18532354168");
// if (map.containsKey(code)) {
// map.put(code, map.get(code) + 1);
// System.err.println("code: " + map.get(code));
// } else {
// map.put(code, 1);
// }
// int rand2 = pos2[new Random().nextInt(pos2.length)];
// String mobile = "1" + rand2 + code;
// System.out.println(mobile);
// }
// Date end = new Date();
// System.out.println("长度: " + (endPos - startPos) + " time:" + (end.getTime() - start.getTime()));
// }
}
package com.yanzuoguang.db.db.dao;
/**
* 数据基本操作接口
* created by yanzu on 2017/5/30.
*/
public interface BaseDao {
/**
* 创建数据,当不传入了主键时,则会自动生成主键,传入时不会生成。
*
* @param model 需要创建的数据
* @return 创建的主键编号
*/
String create(Object model);
/**
* 修改数据
*
* @param model 需要修改的数据
* @return 删除的主键编号
*/
String update(Object model);
/**
* 保存数据,有主键时修改,无主键时创建
*
* @param model 需要保存的数据
* @return 保存的主键编号
*/
String save(Object model);
/**
* 删除数据
*
* @param model 需要删除的数据
* @return 删除的主键编号
*/
String remove(Object model);
/**
* 加载数据
*
* @param model 加载数据的请求参数
* @param cls 需要加载的数据的类型
* @param <T> 返回数据的类型
* @return 需要返回的数据
*/
<T extends Object> T load(Object model, Class<T> cls);
}
package com.yanzuoguang.db.db.dao;
/**
* created by yanzu on 2017/5/30.
*/
public class DaoConst {
public static final int OperatorTypeCreate = 0;
public static final int OperatorTypeUpdate = 1;
public static final int OperatorTypeRemove = 2;
public static final int OperatorTypeLoad = 3;
/**
* 创建
*/
public static final String Create = "create";
/**
* 修改
*/
public static final String Update = "update";
/**
* 删除
*/
public static final String Remove = "remove";
/**
* 加载
*/
public static final String Load = "load";
/**
* 查询
*/
public static final String Query = "query";
/**
* GROUP增加数据的SQL语句
*/
public static final String GroupAdd = "GroupAdd";
/**
* GROUP查询数据的SQL语句
*/
public static final String GroupQuery = "GroupQuery";
}
package com.yanzuoguang.db.db.dao.Impl;
/**
* @Author : Light_PC
* @Description :
* @Date : 2017/12/7 17:36
* @ModiflyAuthor:
* @ModiflyDate: 2017/12/7 17:36
*/
public class CaseSqlModel {
public final static int GroupTypeSUM = 0;
public final static int GroupTypeCOUNT = 1;
public final static int GroupTypeAVG = 2;
public final static int GroupTypeMIN = 3;
public final static int GroupTypeMAX = 4;
public CaseSqlModel(String caseField, String caseValue, String valueField, String toName) {
this(GroupTypeSUM, caseField, caseValue, valueField, toName);
}
public CaseSqlModel(int groupType, String caseField, String caseValue, String valueField, String toName) {
this.GroupType = groupType;
this.CaseField = caseField;
this.CaseValue = caseValue;
this.ValueField = valueField;
this.ToName = toName;
this.AndWhere = "";
}
public CaseSqlModel(String caseField, String caseValue, Object value, String toName, String andWhere) {
this(GroupTypeSUM, caseField, caseValue, value, toName, andWhere);
}
public CaseSqlModel(int groupType, String caseField, String caseValue, Object value, String toName, String andWhere) {
this.GroupType = groupType;
this.CaseField = caseField;
this.CaseValue = caseValue;
this.Value = value;
this.ToName = toName;
this.AndWhere = andWhere;
}
public CaseSqlModel(String caseField, String caseValue, String valueField, String toName, String andWhere) {
this(GroupTypeSUM, caseField, caseValue, valueField, toName, andWhere);
}
public CaseSqlModel(int groupType, String caseField, String caseValue, String valueField, String toName, String andWhere) {
this.GroupType = groupType;
this.CaseField = caseField;
this.CaseValue = caseValue;
this.ValueField = valueField;
this.ToName = toName;
this.AndWhere = andWhere;
}
/**
* 统计纬度
*/
private int GroupType;
/**
* 需要判断的字段
*/
private String CaseField;
/**
* 需要判断的值
*/
private String CaseValue;
/**
* 需要统计的字段,和 Value 只能存在一个,ValueField优先级更高
*/
private String ValueField;
/**
* 需要统计的值,和 ValueField只能存在一个,ValueField优先级更高
*/
private Object Value;
/**
* 目标字段名称
*/
private String ToName;
/**
* 需要判断的CASE字段的附加条件
*/
private String AndWhere;
public int getGroupType() {
return GroupType;
}
public void setGroupType(int groupType) {
GroupType = groupType;
}
public String getCaseField() {
return CaseField;
}
public void setCaseField(String caseField) {
CaseField = caseField;
}
public String getCaseValue() {
return CaseValue;
}
public void setCaseValue(String caseValue) {
CaseValue = caseValue;
}
public String getValueField() {
return ValueField;
}
public void setValueField(String valueField) {
ValueField = valueField;
}
public Object getValue() {
return Value;
}
public void setValue(Object value) {
Value = value;
}
public String getToName() {
return ToName;
}
public void setToName(String toName) {
ToName = toName;
}
public String getAndWhere() {
return AndWhere;
}
public void setAndWhere(String andWhere) {
AndWhere = andWhere;
}
}
package com.yanzuoguang.db.db.dao.Impl;
import java.util.HashMap;
/**
* 行映射
* created by yanzu on 2017/5/31.
*/
public class MapRow extends HashMap<String,Object> {
}
package com.yanzuoguang.db.db.dao.Impl;
import java.util.ArrayList;
import java.util.List;
/**
* SQL语句基本信息
* created by yanzu on 2017/5/30.
*/
public class SqlData {
/**
* 对应的参数顺序
*/
public List<SqlDataField> sqlDataFields = new ArrayList<SqlDataField>();
/**
* SQL语句的名称
*/
public String Name;
/**
* SQL语句
*/
public String Sql;
/**
* 构造函数
*/
public SqlData() {
this("", "");
}
/**
* SQL语句的基本信息
*
* @param name SQL语句的名称
* @param sql 需要执行的SQL语句,其中可以包含大括号括起来的代码片段。 如: {WHERE}
* @param paras SQL语句参数名称数组
*/
public SqlData(String name, String sql, String... paras) {
this.Name = name;
this.Sql = sql;
for (String input : paras) {
this.add(input);
}
}
/**
* 根据字段名称获取字段
*
* @param fieldName
* @return
*/
public SqlDataField getField(String fieldName) {
String to = fieldName.toLowerCase().replaceAll("_", "");
for (SqlDataField sqlDataField : this.sqlDataFields) {
if (to.equals(sqlDataField.paraName.toLowerCase())) {
return sqlDataField;
}
}
return null;
}
/**
* 添加参数,当在SQL语句中存在参数时,用于处理。{@id} 代表前台输入参数字段为id
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE WHERE id=?");
* sql.add( "id" );
* 最终SQL语句为:
* SELECT * FROM TABLE WHERE id={id}"
*
* @param paraName 前台参数名称
*/
public SqlData add(String paraName) {
return addCodeExecute(paraName, "", false);
}
/**
* 添加常规代码片段,即不论如何都会将该代码片段增加到SQL语句中。
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE {INNER} WHERE 1=1 {WHERE}");
* sql.addCode(
* "{INNER}", " INNER JOIN TABLE_B " ,
* "{WHERE}", " AND 1=1" ,
* );
* 最终SQL语句为: (1=1 AND 会自动去掉)
* SELECT * FROM TABLE INNER JOIN TABLE_B WHERE 1=1"
*
* @param codes 代码片段
*/
public SqlData addCode(String... codes) {
return addCodeExecute("", "", false, codes);
}
/**
* 当前台参数传入值时,在 {WHERE} 条件中增加条件,并增加附加的代码片段
* <p>
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE {INNER} WHERE 1=1 {WHERE}");
* sql.add("id" , " AND id = ? ",
* "{INNER}", " INNER JOIN TABLE_B "
* );
* 最终SQL语句为: (1=1 AND 会自动去掉)
* SELECT * FROM TABLE INNER JOIN TABLE_B WHERE id = {@id}
*
* @param paraName 前台参数名称
* @param cond {WHERE}代码片段中的条件
* @param codes 扩展代码片段
*/
public SqlData add(String paraName, String cond, String... codes) {
return addCodeExecute(paraName, cond, true, codes);
}
/**
* 当前台参数传入值时,增加附加的代码片段
* <p>
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE {INNER} WHERE 1=1 {WHERE}");
* sql.addPara("id" ,
* "{WHERE}", " AND id = ? ",
* "{INNER}", " INNER JOIN TABLE_B "
* );
* 最终SQL语句为: (1=1 AND 会自动去掉)
* SELECT * FROM TABLE INNER JOIN TABLE_B WHERE id = {@id}
*
* @param paraName 字段
* @param codes 代码片段
*/
public SqlData addPara(String paraName, String... codes) {
return addCodeExecute(paraName, "", true, codes);
}
/**
* 不论前台参数是否有值,在 {WHERE} 条件中增加条件,并增加附加的代码片段
* <p>
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE {INNER} WHERE 1=1 {WHERE}");
* sql.add("id" , " AND id = ? ",
* "{INNER}", " INNER JOIN TABLE_B "
* );
* 最终SQL语句为: (1=1 AND 会自动去掉)
* SELECT * FROM TABLE INNER JOIN TABLE_B WHERE id = {@id}
*
* @param paraName 前台参数名称
* @param cond {WHERE}代码片段中的条件
* @param codes 扩展代码片段
*/
public SqlData addConst(String paraName, String cond, String... codes) {
return addCodeExecute(paraName, cond, false, codes);
}
/**
* 不论前台参数是否有值,增加代码片段
* <p>
* 例子:
* SqlData sql = new SqlData("SQL_NAME","SELECT * FROM TABLE {INNER} WHERE 1=1 {WHERE}");
* sql.addPara("id" ,
* "{WHERE}", " AND id = ? ",
* "{INNER}", " INNER JOIN TABLE_B "
* );
* 最终SQL语句为: (1=1 AND 会自动去掉)
* SELECT * FROM TABLE INNER JOIN TABLE_B WHERE id = {@id}
*
* @param paraName 前台参数名称
* @param codes 代码片段
*/
public SqlData addParaConst(String paraName, String... codes) {
return addCodeExecute(paraName, "", false, codes);
}
/**
* 添加SQL语句的执行方法
*
* @param paraName 参数名称
* @param cond 包含条件
* @param auto 未false时表示属于必须输入的参数
* @param codes 代码片段
* @return
*/
private SqlData addCodeExecute(String paraName, String cond, boolean auto, String... codes) {
SqlDataField sql = new SqlDataField(paraName, cond);
for (String code : codes) {
sql.codes.add(code);
}
sql.auto = auto;
this.sqlDataFields.add(sql);
return this;
}
/**
* 删除字段
*
* @param fieldName 字段名称
* @return
*/
public SqlData removeField(String fieldName) {
SqlDataField field = this.getField(fieldName);
if (field != null) {
this.sqlDataFields.remove(field);
}
return this;
}
/**
* 删除删除标记字段
*
* @return
*/
public SqlData removeFieldRemove() {
this.removeField(TableStruct.ISREMOVE_CONTANS);
return this;
}
/**
* 将当前SQL语句进行复制
*
* @return 复制的结果
*/
public SqlData copy() {
SqlData to = new SqlData(this.Name, this.Sql);
for (SqlDataField sqlDataField : this.sqlDataFields) {
to.sqlDataFields.add(sqlDataField.copy());
}
return to;
}
/**
* 设置SQL语句名称
*
* @param name SQL语句名称
* @return
*/
public SqlData setName(String name) {
this.Name = name;
return this;
}
}
package com.yanzuoguang.db.db.dao.Impl;
import java.util.ArrayList;
import java.util.List;
/**
* SQL语句的字段
*/
public class SqlDataField {
/**
* 前台参数名称,当没有前台参数时,则把当前字段当常量代码片段处理
*/
public String paraName = "";
/**
* 是否根据前台参数自动添加,false时保持永久添加模式
*/
public boolean auto = true;
/**
* 代码片段
*/
public List<String> codes = new ArrayList<String>();
/**
* 构造函数
*
* @param paraName 前台输入字段
*/
public SqlDataField(String paraName) {
this(paraName, "");
}
/**
* 构造函数
*
* @param paraName 前台输入字段
* @param cond 条件
*/
public SqlDataField(String paraName, String cond) {
this.paraName = paraName;
this.add(cond);
}
/**
* 复制实体
*
* @return
*/
public SqlDataField copy() {
SqlDataField to = new SqlDataField(this.paraName);
to.auto = this.auto;
to.codes.addAll(this.codes);
return to;
}
/**
* 添加条件
*
* @param cond
* @return
*/
public SqlDataField add(String cond) {
return this.add("{WHERE}", cond);
}
/**
* 添加条件
*
* @param codeName 字段名称
* @param codeValue 代码内容
* @return
*/
public SqlDataField add(String codeName, String codeValue) {
if ("".equals(codeValue) || codeValue == null) {
return this;
}
this.codes.add(codeName);
this.codes.add(codeValue);
return this;
}
/**
* 清除所有的代码片段
*
* @return
*/
public SqlDataField clear() {
this.codes.clear();
return this;
}
}
package com.yanzuoguang.db.db.dao.Impl;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yanzu on 2017/6/6.
*/
public class TableFieldString {
/**
* 其他字段
*/
public List<String> Fields = new ArrayList<String>();
/**
* 构造函数
*
* @param fields
*/
public TableFieldString(String... fields) {
for (String field : fields) {
this.Fields.add(field);
}
}
/**
* 构造函数
*
* @param fields
*/
public TableFieldString(List<String> fields) {
for (String field : fields) {
this.Fields.add(field);
}
}
}
package com.yanzuoguang.db.db.dao.Impl;
/**
* 表结构的基本信息
* created by yanzu on 2017/5/30.
*/
public class TableFieldVo {
public TableFieldVo() {
this("id");
}
public TableFieldVo(String name) {
this(name, name);
}
public TableFieldVo(String name, String inputName) {
this(name, inputName, String.class);
}
public TableFieldVo(String name, String inputName, Class<?> type) {
this.name = name;
this.lName = name.toLowerCase();
this.inputName = inputName;
this.inputLName = inputName.toLowerCase();
this.type = type;
}
public String name;
public String lName;
public String inputName;
public String inputLName;
public Class<?> type = String.class;
;
}
package com.yanzuoguang.db.db.dao.Impl;
import com.yanzuoguang.util.cache.MemoryCache;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.StringHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 缓存的SQL语句信息
* created by yanzu on 2017/5/30.
*/
public class TableSqlCache {
/**
* 分页标记
*/
public static final String PAGE_SIZE_TAG = "_PageSize";
/**
* 表信息
*/
public TableStruct Table;
/**
* 缓存的SQL信息
*/
public MemoryCache<SqlData> Sqls = new MemoryCache<SqlData>();
/**
* 构造函数
*/
public TableSqlCache() {
this.Table = new TableStruct();
}
/**
* 添加SQL语句组
*
* @param sqls
*/
public void add(SqlData... sqls) {
for (SqlData sql : sqls) {
this.add(sql);
}
}
/**
* 添加可执行的SQL语句
*
* @param sql SQL语句
*/
public SqlData add(SqlData sql) {
if (sql != null) {
this.Sqls.put(sql.Name, sql);
}
return sql;
}
/**
* 添加SQL
*
* @param sqlName SQL名称
* @param sql SQL语句
* @param fields 字段
*/
public SqlData add(String sqlName, String sql, String... fields) {
SqlData model = new SqlData(sqlName, sql, fields);
return this.add(model);
}
/**
* 根据现有SQL语句生成分页查询
*
* @param from
* @param sql
* @return
*/
public SqlData addPageSize(SqlData from, String sql) {
SqlData to = from.copy();
to.Sql = sql;
to.Name += TableSqlCache.PAGE_SIZE_TAG;
return this.add(to);
}
/**
* 生成GroupSQL语句
*
* @param tableWhereField
* @param addField
*/
public void addGroup(TableFieldString tableWhereField, TableFieldString addField) {
this.Table.addGroupSql(this, tableWhereField, addField);
}
/**
* 生成GroupSQL语句
*
* @param sqlName
* @param whereFields
*/
public void addSaveWith(String sqlName, TableFieldString whereFields) {
this.Table.addSaveWithSql(this, sqlName, whereFields);
}
/**
* 生成Group执行的SQL语句
*
* @param sqlName
* @param tableWhereField
* @param addField
* @param sql
* @param
*/
public List<SqlData> addGroupList(String sqlName, TableFieldString tableWhereField, TableFieldString addField,
String sql, String... field) {
Map<String, Boolean> sqlFieldHas = new HashMap<String, Boolean>();
Map<String, Boolean> sqlFieldWhere = new HashMap<String, Boolean>();
Map<String, Boolean> sqlFieldAdd = new HashMap<String, Boolean>();
SqlData sqlInit = new SqlData(sqlName + "_GroupInit", "", field);
SqlData sqlAdd = new SqlData(sqlName + "_GroupAdd", "", field);
// 1. 获取SQL语句中已包含的字段
String sqlField = sql.substring(0, sql.replace("\n", " ")
.replace("\t", " ")
.toLowerCase().indexOf(" from ")) + ",";
// 去掉字段中的函数
sqlField = sqlField.replaceAll("\\(.+?\\)", "");
String regex = "[\\s,]*(\\S+?)\\s*?,";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sqlField);
// 寻找到的代码片段 不包含分括号
while (m.find()) {
String name = m.group(1);
if (name.indexOf(".") >= -1) {
name = name.substring(name.indexOf(".") + 1);
}
sqlFieldHas.put(name.toLowerCase(), true);
}
// 2. 判断所有纬度字段是否已经存在
for (String item : tableWhereField.Fields) {
String name = item.toLowerCase();
if (!sqlFieldHas.containsKey(name)) {
throw new CodeException("SQL语句" + item + "不存在纬度" + item);
}
sqlFieldWhere.put(name, true);
}
for (String item : addField.Fields) {
String name = item.toLowerCase();
sqlFieldAdd.put(name, true);
}
// 3. 生成SQL语句
String selectModel = "SELECT {FromField} FROM ( {SQL} )t";
String initModel = "INSERT INTO {Table}( {CreateField} ) " +
"SELECT {FromInitField} FROM( {SelectSQL} )a " +
"LEFT JOIN {Table} AS b ON a.{Key} = b.{Key} WHERE b.{Key} IS NULL";
String addModel = "UPDATE {Table} AS a INNER JOIN ( {SelectSQL} ) AS b ON a.{Key} = b.{Key} SET {addConst} ";
// 定义需要处理的SQL对象
Map<String, StringBuilder> map = new HashMap<String, StringBuilder>();
addString(map, "{SQL}", sql);
addString(map, "{Table}", this.Table.getName());
if (this.Table.getKeyType() == String.class) {
addString(map, "{Key}", this.Table.getKeyName());
} else if (!StringHelper.isEmpty(this.Table.getMD5KeyName())) {
addString(map, "{Key}", this.Table.getMD5KeyName());
} else {
throw new CodeException("表中未包含MD5字段");
}
String lowerKey = this.Table.getKeyName().toLowerCase();
String lowerMD5Key = this.Table.getMD5KeyName().toLowerCase();
List<TableFieldVo> allField = new ArrayList<TableFieldVo>();
allField.add(this.Table.getKey());
allField.addAll(this.Table.getFields());
for (TableFieldVo fieldVo : allField) {
String fieldName = fieldVo.name;
String fieldLName = fieldVo.lName;
if (fieldLName.equals(lowerKey) && this.Table.getKeyType() != String.class) {
continue;
}
// 处理逗号
addFlag(map, "{CreateField}", ",");
addFlag(map, "{FromInitField}", ",");
addString(map, "{CreateField}", fieldName);
if (fieldLName.equals(lowerKey) || fieldLName.equals(lowerMD5Key)) {
addFlag(map, "{FromField}", ",");
// 处理需要MD5的字段
addString(map, "{FromField}", "MD5(CONCAT(");
int i = 0;
for (String whereField : tableWhereField.Fields) {
if (i > 0) {
addString(map, "{FromField}", ",':',");
}
addString(map, "{FromField}", whereField);
i++;
}
addString(map, "{FromField}", ")) AS ");
addString(map, "{FromField}", fieldName);
addString(map, "{FromInitField}", "a." + fieldName);
} else {
// 处理常规字段
if (sqlFieldAdd.containsKey(fieldLName) && sqlFieldHas.containsKey(fieldLName)) {
addFlag(map, "{addConst}", ",");
addString(map, "{addConst}", "a." + fieldName + "=a." + fieldName + "+b." + fieldName);
}
if (sqlFieldHas.containsKey(fieldLName)) {
addFlag(map, "{FromField}", ",");
addString(map, "{FromField}", fieldName);
}
if (sqlFieldWhere.containsKey(fieldLName)) {
addString(map, "{FromInitField}", "a." + fieldName);
} else if (sqlFieldAdd.containsKey(fieldLName)) {
addString(map, "{FromInitField}", "0 AS " + fieldName);
} else {
addString(map, "{FromInitField}", "a." + fieldName);
System.err.println("纬度" + this.Table.getName() + "->" + sqlName + "->" + fieldName + "存在,但是没有统计");
}
}
}
// 最终SQL语句处理
selectModel = replaceString(map, selectModel);
addString(map, "{SelectSQL}", selectModel);
sqlInit.Sql = replaceString(map, initModel);
sqlAdd.Sql = replaceString(map, addModel);
this.add(sqlInit);
this.add(sqlAdd);
List<SqlData> ret = new ArrayList<SqlData>();
ret.add(sqlInit);
ret.add(sqlAdd);
return ret;
}
/**
* 生成该字段值是否存在的SQL语句
*
* @param sqlName SQL语句名称
* @param fields 字段
*/
public void addExist(String sqlName, String... fields) {
this.Table.addExist(this, sqlName, fields);
}
private void addString(Map<String, StringBuilder> map, String name, String value) {
if (!map.containsKey(name)) {
map.put(name, new StringBuilder());
}
map.get(name).append(value);
}
private void addFlag(Map<String, StringBuilder> map, String name, String flag) {
if (!map.containsKey(name)) {
addString(map, name, "");
} else if (map.get(name).length() > 0) {
addString(map, name, flag);
}
}
private String replaceString(Map<String, StringBuilder> map, String sql) {
for (String key : map.keySet()) {
sql = sql.replace(key, map.get(key).toString());
}
return sql;
}
}
package com.yanzuoguang.db.db.dao;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 途比达列明映射
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface TableAnnotation {
/**
* 名称
*
* @return
*/
String value();
}
package com.yanzuoguang.db.db.extend;
/**
* 打印SQL日志
*/
public class ConfigDb {
/**
* 打印映射日志
*/
public static final boolean PrintMapper = false;
/**
* 打印SQL日志
*/
public static boolean PrintSql = false;
/**
* 判断是否匹配过滤
*/
public static String PrintSqlFilter = "";
}
package com.yanzuoguang.db.db.service;
import java.util.List;
/**
* 基本服务接口
* created by yanzu on 2017/5/29.
*/
public interface BaseService<T> {
/**
* 创建数据
*
* @param models 需要创建的数据
*/
List<String> create(T... models);
/**
* 修改数据
*
* @param models 需要修改的数据
*/
List<String> update(T... models);
/**
* 保存数据
*
* @param models 需要保存的数据
*/
List<String> save(T... models);
/**
* 删除数据
*
* @param models 需要删除的数据
*/
List<String> remove(T... models);
/**
* 加载数据
*
* @param models 需要删除的数据
*/
List<T> load(T... models);
}
package com.yanzuoguang.db.db.service.Impl;
import com.yanzuoguang.db.db.dao.BaseDao;
import com.yanzuoguang.db.db.service.BaseService;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.StringHelper;
import java.util.ArrayList;
import java.util.List;
/**
* 基本服务实现
* created by yanzu on 2017/5/31.
*/
public abstract class BaseServiceImpl<T> implements BaseService<T> {
/**
* 数据类的类型
*/
protected Class<T> dataClass;
/**
* 标识
*/
protected String tag;
/**
* 构造函数
*
* @param cls
*/
public BaseServiceImpl(Class<T> cls, String tag) {
this.dataClass = cls;
this.tag = tag;
}
/**
* @param
* @return
* @description 获取Dao类来处理
*/
protected abstract BaseDao getDao();
/**
* 创建数据
*
* @param models 需要创建的数据
*/
public List<String> create(T... models) {
List<String> ids = new ArrayList<String>();
for (T t : models) {
String id = createItem(t);
ids.add(id);
}
return ids;
}
/**
* 创建一项
*
* @param item
* @return
*/
protected String createItem(T item) {
String id = this.getDao().create(item);
check("创建", this.tag, id);
return id;
}
/**
* 修改数据
*
* @param models 需要修改的数据
*/
public List<String> update(T... models) {
List<String> ids = new ArrayList<String>();
for (T t : models) {
String id = updateItem(t);
ids.add(id);
}
return ids;
}
/**
* 修改一项数据
*
* @param item
* @return
*/
protected String updateItem(T item) {
String id = this.getDao().update(item);
check("修改", this.tag, id);
return id;
}
/**
* 保存数据
*
* @param models 需要保存的数据
*/
public List<String> save(T... models) {
List<String> ids = new ArrayList<String>();
for (T item : models) {
String id = saveItem(item);
ids.add(id);
}
return ids;
}
/**
* 保存其中一项
*
* @param item
* @return
*/
protected String saveItem(T item) {
String id = this.getDao().save(item);
check("保存", this.tag, id);
return id;
}
/**
* 删除数据
*
* @param models 需要删除的数据
*/
public List<String> remove(T... models) {
List<String> ids = new ArrayList<String>();
for (T item : models) {
String id = removeItem(item);
ids.add(id);
}
return ids;
}
/**
* 删除其中一项
*
* @param item
* @return
*/
protected String removeItem(T item) {
String id = this.getDao().remove(item);
check("删除", this.tag, id);
return id;
}
/**
* 加载数据
*
* @param models 需要删除的数据
*/
public List<T> load(T... models) {
List<T> tos = new ArrayList<T>();
for (T item : models) {
T to = loadItem(item);
tos.add(to);
}
return tos;
}
/**
* 加载单个数据
*
* @param item
* @return
*/
protected T loadItem(T item) {
T to = this.getDao().load(item, dataClass);
check("加载", this.tag, to);
return to;
}
/**
* 检测编号
*
* @param opTag 操作标识
* @param serviceTag 服务标识
* @param id ID编号
*/
private void check(String opTag, String serviceTag, Object id) {
if (StringHelper.isEmpty(id)) {
throw new CodeException(opTag + serviceTag + "失败,该数据可能已被修改");
}
}
}
package com.yanzuoguang.extend;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 打印SQL日志
*/
@Component
public class ConfigDb {
/**
* 打印映射日志
*/
public static final boolean PrintMapper = false;
@Value("${yzg.PrintMapper:true}")
private boolean PrintMapper;
/**
* 打印SQL日志
*/
public static boolean PrintSql = false;
@Value("${yzg.PrintSql:true}")
private boolean PrintSql;
/**
* 判断是否匹配过滤
*/
public static String PrintSqlFilter = "";
@Value("${yzg.PrintSqlFilter:}")
private String PrintSqlFilter;
public boolean isPrintMapper() {
return PrintMapper;
}
public boolean isPrintSql() {
return PrintSql;
}
public String getPrintSqlFilter() {
return PrintSqlFilter;
}
}
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