添加maper事务支持

main
youHong.ai 2022-12-21 23:02:27 +08:00
parent 242080e581
commit 958a9d7029
16 changed files with 998 additions and 54 deletions

1
.gitignore vendored
View File

@ -43,6 +43,7 @@ DirectoryV2.xml
src/main/resources/WEB-INF/sqllog/
java.io.tempdir/
ecology-9-dev.iml
src/test/resources/font

View File

@ -1976,6 +1976,43 @@ public class Util extends weaver.general.Util {
return recordsetUtil.getMapper(t);
}
/**
* <h2>getTransMapper mapper</h2>
* <i>2022/12/21 22:45</i>
* ************************************************************
*
* @param t
* @param <T>
* @return T
* @author youHong.ai ******************************************
*/
public static <T> T getTransMapper(Class<T> t) {
return recordsetUtil.getMapper(t, false);
}
/**
* <h2>commitTransMapper mapper</h2>
* <i>2022/12/21 22:46</i>
* ************************************************************
*
* @return boolean
* @author youHong.ai ******************************************
*/
public static boolean commitTransMapper() {
return recordsetUtil.getRsManager().commit();
}
/**
* <h2>rollbackTransMapper mapper </h2>
* <i>2022/12/21 22:46</i>
* ************************************************************
*
* @return boolean
* @author youHong.ai ******************************************
*/
public static boolean rollbackTransMapper() {
return recordsetUtil.getRsManager().rollback();
}
/**
* join

View File

@ -6,12 +6,12 @@ import aiyh.utils.excention.CustomerException;
import com.google.common.base.Strings;
import org.jetbrains.annotations.NotNull;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:34
* @author EBU7-dev1-ayh create 2021/12/21 0021 13:34
*/
@ -26,6 +26,16 @@ public class BooleanTypeHandler implements TypeHandler{
return getBoolean(declaredField, rs.getString(index));
}
@Override
public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) {
return getBoolean(declaredField, rs.getString(fieldName));
}
@Override
public Object getValue(RecordSetTrans rs, int index, Field declaredField) {
return getBoolean(declaredField, rs.getString(index));
}
@NotNull
private Object getBoolean(Field declaredField, String fieldValue) {
try {

View File

@ -4,14 +4,14 @@ import aiyh.utils.annotation.DateFormatAn;
import aiyh.utils.excention.TypeNonsupportException;
import com.ibm.icu.text.SimpleDateFormat;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Date;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:35
* @author EBU7-dev1-ayh create 2021/12/21 0021 13:35
*/
@ -53,4 +53,42 @@ public class DataTypeHandler implements TypeHandler {
}
return date;
}
@Override
public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(fieldName));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(fieldName) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
@Override
public Object getValue(RecordSetTrans rs, int index, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(index));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(index) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
}

View File

@ -2,6 +2,7 @@ package aiyh.utils.recordset;
import aiyh.utils.Util;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
@ -24,4 +25,16 @@ public class FloatTypeHandler implements TypeHandler {
String string = Util.null2DefaultStr(rs.getString(index), "0.0");
return Float.parseFloat(string);
}
@Override
public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(fieldName), "0.0");
return Float.parseFloat(string);
}
@Override
public Object getValue(RecordSetTrans rs, int index, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(index), "0.0");
return Float.parseFloat(string);
}
}

View File

@ -2,12 +2,12 @@ package aiyh.utils.recordset;
import aiyh.utils.Util;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:10
* @author EBU7-dev1-ayh create 2021/12/21 0021 13:10
*/
@ -29,4 +29,22 @@ public class IntegerTypeHandler implements TypeHandler{
}
return Integer.parseInt(string);
}
@Override
public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(fieldName), "-1");
if (string.contains(".")) {
string = string.substring(0, string.indexOf("."));
}
return Integer.parseInt(string);
}
@Override
public Object getValue(RecordSetTrans rs, int index, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(index), "-1");
if (string.contains(".")) {
string = string.substring(0, string.indexOf("."));
}
return Integer.parseInt(string);
}
}

View File

@ -7,10 +7,13 @@ import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
/**
* @author EBU7-dev1-ayh create 2021/12/19 0019 14:39
@ -19,24 +22,43 @@ import java.lang.reflect.Proxy;
public class RecordsetUtil implements InvocationHandler {
private final RecordSet recordSet = new RecordSet();
private final RecordSet rs = new RecordSet();
public static final String SQL_LOG = "sql_log";
private final RsThreadLocalManager rsManager = new RsThreadLocalManager();
private boolean autoCommit = true;
public <T> T getMapper(Class<T> tClass) {
return getMapper(tClass, true);
}
public <T> T getMapper(Class<T> tClass, boolean autoCommit) {
if (tClass == null) {
throw new BindingException("class is null!");
}
if (tClass.getAnnotation(SqlMapper.class) == null) {
throw new BindingException("can not find SqlMapper annotation!");
}
this.autoCommit = autoCommit;
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
if (autoCommit) {
return invokeRs(proxy, method, args);
}
return invokeRsTrans(proxy, method, args);
}
private Object invokeRs(Object proxy, Method method, Object[] args) {
RecordSet rs = rsManager.getRs();
if (rs == null) {
rsManager.setRecordSet();
rs = rsManager.getRs();
}
SqlHandler sqlHandler = new SqlHandler();
ResultMapper resultMapper = new ResultMapper();
Select select = method.getAnnotation(Select.class);
@ -48,7 +70,7 @@ public class RecordsetUtil implements InvocationHandler {
if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) {
throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!");
}
Util.getLogger("sql_log").info("解析sql===>" + handler);
Util.getLogger(SQL_LOG).info("解析sql===>" + handler);
if (handler.getArgs().isEmpty()) {
rs.executeQuery(handler.getSqlStr());
} else {
@ -57,7 +79,6 @@ public class RecordsetUtil implements InvocationHandler {
return resultMapper.mapperResult(rs, method, method.getReturnType());
}
Update update = method.getAnnotation(Update.class);
if (update != null) {
// 查询
String sql = update.value();
@ -66,13 +87,13 @@ public class RecordsetUtil implements InvocationHandler {
if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) {
throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!");
}
Util.getLogger("sql_log").info(handler.toString());
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr());
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
@ -97,13 +118,13 @@ public class RecordsetUtil implements InvocationHandler {
if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) {
throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!");
}
Util.getLogger("sql_log").info(handler.toString());
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr());
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
@ -121,13 +142,13 @@ public class RecordsetUtil implements InvocationHandler {
if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) {
throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!");
}
Util.getLogger("sql_log").info(handler.toString());
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr());
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
@ -143,14 +164,14 @@ public class RecordsetUtil implements InvocationHandler {
Class<?> returnType = method.getReturnType();
boolean custom = batchInsert.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString());
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) {
throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!");
}
boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) {
return null;
}
@ -166,14 +187,14 @@ public class RecordsetUtil implements InvocationHandler {
Class<?> returnType = method.getReturnType();
boolean custom = batchUpdate.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString());
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) {
throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!");
}
boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) {
return null;
}
@ -189,14 +210,14 @@ public class RecordsetUtil implements InvocationHandler {
Class<?> returnType = method.getReturnType();
boolean custom = batchDelete.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString());
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) {
throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!");
}
boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
boolean b = rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) {
return null;
}
@ -208,4 +229,255 @@ public class RecordsetUtil implements InvocationHandler {
throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete");
}
private Object invokeRsTrans(Object proxy, Method method, Object[] args) {
RecordSetTrans rs = rsManager.getTrans();
if (rs == null) {
rsManager.setRecordSetTrans();
rs = rsManager.getTrans();
}
SqlHandler sqlHandler = new SqlHandler();
ResultMapper resultMapper = new ResultMapper();
Select select = method.getAnnotation(Select.class);
if (select != null) {
// 查询
String sql = select.value();
boolean custom = select.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) {
throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId the select statement, please check whether the sql statement matches!");
}
Util.getLogger(SQL_LOG).info("解析sql===>" + handler);
try {
if (handler.getArgs().isEmpty()) {
rs.executeQuery(handler.getSqlStr());
} else {
rs.executeQuery(handler.getSqlStr(), handler.getArgs());
}
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
return resultMapper.mapperResult(rs, method, method.getReturnType());
}
Update update = method.getAnnotation(Update.class);
if (update != null) {
// 查询
String sql = update.value();
boolean custom = update.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) {
throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!");
}
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
try {
if (handler.getArgs().isEmpty()) {
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(int.class) || returnType.equals(Integer.class)) {
if (b) {
return 1;
} else {
return 0;
}
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Insert insert = method.getAnnotation(Insert.class);
if (insert != null) {
// 查询
String sql = insert.value();
boolean custom = insert.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) {
throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!");
}
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
try {
if (handler.getArgs().isEmpty()) {
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Delete delete = method.getAnnotation(Delete.class);
if (delete != null) {
// 查询
String sql = delete.value();
boolean custom = delete.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) {
throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!");
}
Util.getLogger(SQL_LOG).info(handler.toString());
Class<?> returnType = method.getReturnType();
boolean b;
try {
if (handler.getArgs().isEmpty()) {
b = rs.executeUpdate(handler.getSqlStr());
} else {
b = rs.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class);
if (hasBatchInsert) {
BatchInsert batchInsert = method.getAnnotation(BatchInsert.class);
String sql = batchInsert.value();
Class<?> returnType = method.getReturnType();
boolean custom = batchInsert.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
List<List> batchList = batchSqlResult.getBatchList();
if (batchList.isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
List<List<Object>> batchListTrans = new ArrayList<>();
for (List list : batchList) {
List<Object> listItem = new ArrayList<>();
for (Object o : list) {
listItem.add(o);
}
batchListTrans.add(listItem);
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) {
throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId the insert statement, please check whether the sql statement matches!");
}
boolean b = true;
try {
rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans);
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class);
if (hasBatchUpdate) {
BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class);
String sql = batchUpdate.value();
Class<?> returnType = method.getReturnType();
boolean custom = batchUpdate.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) {
throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId the update statement, please check whether the sql statement matches!");
}
List<List> batchList = batchSqlResult.getBatchList();
if (batchList.isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
List<List<Object>> batchListTrans = new ArrayList<>();
for (List list : batchList) {
List<Object> listItem = new ArrayList<>();
for (Object o : list) {
listItem.add(o);
}
batchListTrans.add(listItem);
}
try {
rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans);
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return true;
}
}
boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class);
if (hasBatchDelete) {
BatchDelete batchDelete = method.getAnnotation(BatchDelete.class);
String sql = batchDelete.value();
Class<?> returnType = method.getReturnType();
boolean custom = batchDelete.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger(SQL_LOG).info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) {
throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId the delete statement, please check whether the sql statement matches!");
}
List<List> batchList = batchSqlResult.getBatchList();
if (batchList.isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!");
}
List<List<Object>> batchListTrans = new ArrayList<>();
for (List list : batchList) {
List<Object> listItem = new ArrayList<>();
for (Object o : list) {
listItem.add(o);
}
batchListTrans.add(listItem);
}
try {
rs.executeBatchSql(batchSqlResult.getSqlStr(), batchListTrans);
} catch (Exception e) {
Util.getLogger(SQL_LOG).error("execute sql error! " + Util.getErrString(e));
throw new CustomerException("execute sql error!" + e.getMessage());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return true;
}
}
throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete");
}
public RsThreadLocalManager getRsManager() {
return rsManager;
}
}

View File

@ -15,8 +15,7 @@ import java.lang.reflect.*;
import java.util.*;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 11:03
* @author EBU7-dev1-ayh create 2021/12/21 0021 11:03
*/
@ -143,6 +142,222 @@ public class ResultMapper {
return null;
}
public <T> T mapperResult(RecordSetTrans rs, Method method, Class<T> tClass) {
if (tClass.equals(void.class)) {
return null;
}
if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) {
return (T) rs;
}
try {
if (tClass.equals(List.class)) {
tClass = (Class<T>) ArrayList.class;
}
if (tClass.equals(Map.class)) {
tClass = (Class<T>) HashMap.class;
}
if (ResultMapper.typeHandler.containsKey(tClass)) {
rs.next();
return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null);
}
T t = tClass.newInstance();
if (t instanceof Collection) {
// 集合求出泛型
//获取返回值的类型
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
while (rs.next()) {
Object o = null;
try {
Constructor<?> constructor = rawType.getConstructor();
o = constructor.newInstance();
} catch (NoSuchMethodException | InvocationTargetException ignored) {
if (Number.class.isAssignableFrom(rawType)) {
Constructor<?> constructor;
try {
constructor = rawType.getConstructor(String.class);
o = constructor.newInstance("-1");
} catch (NoSuchMethodException | InvocationTargetException e) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e);
}
}
}
if (o == null) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]");
}
Object object = getObjectTrans(rs, o, method);
((Collection<? super Object>) t).add(object);
}
return t;
}
if (t instanceof Map) {
// map
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(List.class)) {
rawType = (Class<T>) ArrayList.class;
}
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
// Object o = rawType.newInstance();
Object o = null;
try {
Constructor<?> constructor = rawType.getConstructor();
o = constructor.newInstance();
} catch (NoSuchMethodException | InvocationTargetException ignored) {
if (Number.class.isAssignableFrom(rawType)) {
Constructor<?> constructor;
try {
constructor = rawType.getConstructor(String.class);
o = constructor.newInstance("-1");
} catch (NoSuchMethodException | InvocationTargetException e) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e);
}
}
}
if (o == null) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]");
}
if (o instanceof Map || o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (rs.next()) {
return (T) getObjectTrans(rs, t, method);
}
return null;
}
if (t.getClass().isArray()) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (rs.next()) {
return (T) getObjectTrans(rs, t, method);
}
return null;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Object getObjectTrans(RecordSetTrans rs, Object o, Method method) {
CaseConversion annotation = method.getAnnotation(CaseConversion.class);
boolean enable = annotation == null ? true : annotation.value();
String[] columnName = rs.getColumnName();
String[] columnTypeName = rs.getColumnTypeName();
int[] columnTypes = rs.getColumnType();
if (columnTypeName == null) {
columnTypeName = new String[columnTypes.length];
for (int i = 0; i < columnTypes.length; i++) {
int type = columnTypes[i];
switch (type) {
case -1:
columnTypeName[i] = "TEXT";
break;
case 4:
columnTypeName[i] = "INT";
break;
case 12:
columnTypeName[i] = "VARCHAR";
break;
default:
columnTypeName[i] = "VARCHAR";
}
}
}
try {
if (o instanceof Map) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getInt(i + 1));
continue;
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1));
continue;
}
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1));
continue;
}
return o;
}
if (o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (o instanceof Number) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
return rs.getInt(i + 1);
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
return rs.getFloat(i + 1);
}
}
return o;
}
if (o instanceof String) {
for (int i = 0; i < columnName.length; i++) {
return rs.getString(i + 1);
}
return o;
}
if (o instanceof Boolean) {
for (int i = 0; i < columnName.length; i++) {
return rs.getBoolean(i + 1);
}
return o;
}
// Util.getLogger().info("获取对象:" + o.toString());
BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object value = null;
String fieldName = propertyDescriptor.getName();
if (Strings.isNullOrEmpty(fieldName)) {
fieldName = propertyDescriptor.getDisplayName();
}
// Util.getLogger().info("获取类字段:" + fieldName);
// Util.getLogger().info("获取类字段1" + propertyDescriptor.getDisplayName());
// Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName));
Field declaredField = o.getClass().getDeclaredField(fieldName);
if (enable) {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField);
} else {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField);
}
propertyDescriptor.getWriteMethod().invoke(o, value);
}
} catch (Exception e) {
e.printStackTrace();
Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e));
}
return o;
}
public Object getObject(RecordSet rs, Object o, Method method) {
CaseConversion annotation = method.getAnnotation(CaseConversion.class);
boolean enable = annotation == null ? true : annotation.value();

View File

@ -0,0 +1,209 @@
package aiyh.utils.recordset;
import aiyh.utils.excention.CustomerException;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* <h1>ThreadLocal</h1>
*
* <p>create: 2022-12-21 21:31</p>
*
* @author youHong.ai
*/
public class RsThreadLocalManager {
private final ConcurrentHashMap<Long, RsThreadLocalMap> rsMap = new ConcurrentHashMap<>();
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
public RsThreadLocalManager() {
startMonitor();
}
/**
* <h2>rs</h2>
* <i>2022/12/21 22:02</i>
* ************************************************************
*
* @author youHong.ai ******************************************
*/
private void startMonitor() {
executor.scheduleAtFixedRate(this::checkExpireRs, 0, 2, TimeUnit.MINUTES);
}
/**
* <h2>checkExpireRs rs</h2>
* <i>2022/12/21 22:02</i>
* ************************************************************
*
* @author youHong.ai ******************************************
*/
private void checkExpireRs() {
Iterator<Map.Entry<Long, RsThreadLocalMap>> iterator = rsMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, RsThreadLocalMap> entity = iterator.next();
RsThreadLocalMap value = entity.getValue();
if (System.currentTimeMillis() >= value.getExpireTime() || value.getExpireTime() != -1) {
iterator.remove();
}
}
}
/**
* <h2>setRecordSet 线rs</h2>
* <i>2022/12/21 22:03</i>
* ************************************************************
*
* @author youHong.ai ******************************************
*/
public void setRecordSet() {
RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(new RecordSet(), getExpireTime());
rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap);
}
/**
* <h2>setRecordSet 线</h2>
* <i>2022/12/21 22:03</i>
* ************************************************************
*
* @author youHong.ai ******************************************
*/
public void setRecordSetTrans() {
RecordSetTrans recordSetTrans = new RecordSetTrans();
recordSetTrans.setAutoCommit(false);
RsThreadLocalMap rsThreadLocalMap = new RsThreadLocalMap(recordSetTrans, -1L);
rsMap.put(Thread.currentThread().getId(), rsThreadLocalMap);
}
/**
* <h2>getExpireTime </h2>
* <i>2022/12/21 22:06</i>
* ************************************************************
*
* @return Long
* @author youHong.ai ******************************************
*/
public Long getExpireTime() {
return System.currentTimeMillis() + 1000L * 60 * 3;
}
/**
* <h2>getRs 线rs</h2>
* <i>2022/12/21 22:04</i>
* ************************************************************
*
* @return RecordSet
* @author youHong.ai ******************************************
*/
public RecordSet getRs() {
RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId());
if (Objects.isNull(rsThreadLocalMap)) {
return null;
}
rsThreadLocalMap.setExpireTime(getExpireTime());
return rsThreadLocalMap.getRecordSet();
}
/**
* <h2>getTrans 线rs</h2>
* <i>2022/12/21 22:04</i>
* ************************************************************
*
* @return RecordSetTrans rs
* @author youHong.ai ******************************************
*/
public RecordSetTrans getTrans() {
RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId());
if (Objects.isNull(rsThreadLocalMap)) {
return null;
}
rsThreadLocalMap.setExpireTime(-1L);
return rsThreadLocalMap.getRecordSetTrans();
}
public boolean commit() {
RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId());
if (Objects.isNull(rsThreadLocalMap)) {
throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java");
}
rsThreadLocalMap.setExpireTime(getExpireTime());
RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans();
return recordSetTrans.commit();
}
public boolean rollback() {
RsThreadLocalMap rsThreadLocalMap = rsMap.get(Thread.currentThread().getId());
if (Objects.isNull(rsThreadLocalMap)) {
throw new CustomerException("can not find RecordSetTrans instance! please Contact the developer of RecordsetUtil.java");
}
rsThreadLocalMap.setExpireTime(getExpireTime());
RecordSetTrans recordSetTrans = rsThreadLocalMap.getRecordSetTrans();
return recordSetTrans.rollback();
}
/**
* <h2>remove 线rs</h2>
* <i>2022/12/21 22:05</i>
* ************************************************************
*
* @author youHong.ai ******************************************
*/
public void remove() {
rsMap.remove(Thread.currentThread().getId());
}
static class RsThreadLocalMap {
private RecordSet recordSet;
private RecordSetTrans recordSetTrans;
private Long expireTime;
public RsThreadLocalMap(RecordSet recordSet, Long expireTime) {
this.recordSet = recordSet;
this.expireTime = expireTime;
}
public RsThreadLocalMap(RecordSetTrans recordSetTrans, Long expireTime) {
this.recordSetTrans = recordSetTrans;
this.expireTime = expireTime;
}
public RecordSetTrans getRecordSetTrans() {
return recordSetTrans;
}
public void setRecordSetTrans(RecordSetTrans recordSetTrans) {
this.recordSetTrans = recordSetTrans;
}
public RecordSet getRecordSet() {
return recordSet;
}
public void setRecordSet(RecordSet recordSet) {
this.recordSet = recordSet;
}
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
}
}

View File

@ -1,12 +1,12 @@
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:06
* @author EBU7-dev1-ayh create 2021/12/21 0021 13:06
*/
@ -20,4 +20,14 @@ public class StringTypeHandler implements TypeHandler{
public Object getValue(RecordSet rs, int index, Field declaredField) {
return rs.getString(index);
}
@Override
public Object getValue(RecordSetTrans rs, String fieldName, Field declaredField) {
return rs.getString(fieldName);
}
@Override
public Object getValue(RecordSetTrans rs, int index, Field declaredField) {
return rs.getString(index);
}
}

View File

@ -1,15 +1,20 @@
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import java.lang.reflect.Field;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/21 0021 13:05
* @author @author EBU7-dev1-ay create 2021/12/21 0021 13:05
*/
public interface TypeHandler {
Object getValue(RecordSet rs, String fieldName, Field declaredField);
Object getValue(RecordSet rs, int index, Field declaredField);
Object getValue(RecordSetTrans rs, String fieldName, Field declaredField);
Object getValue(RecordSetTrans rs, int index, Field declaredField);
}

View File

@ -0,0 +1,27 @@
package weaver.youhong.ai.fentian.renamefile.action;
import aiyh.utils.Util;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.ActionDesc;
import lombok.Setter;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.youhong.ai.fentian.renamefile.mapper.RenameDocFileMapper;
/**
* <h1></h1>
*
* <p>create: 2022-12-15 11:38</p>
*
* @author youHong.ai
*/
@ActionDesc(value = "重命名流程字段中的附件字段的附件名称",author = "youhong.ai")
@Setter
public class RenameDocFile extends SafeCusBaseAction {
private final RenameDocFileMapper mapper = Util.getMapper(RenameDocFileMapper.class);
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
}
}

View File

@ -0,0 +1,15 @@
package weaver.youhong.ai.fentian.renamefile.mapper;
import aiyh.utils.annotation.recordset.SqlMapper;
/**
* <h1></h1>
*
* <p>create: 2022-12-15 11:40</p>
*
* @author youHong.ai
*/
@SqlMapper
public interface RenameDocFileMapper {
}

View File

@ -0,0 +1,33 @@
package youhong.ai.pcn;
import aiyh.utils.Util;
import basetest.BaseTest;
import ebu7common.youhong.ai.bean.Builder;
import org.junit.Test;
import youhong.ai.pcn.mapper.TransTestMapper;
import youhong.ai.pcn.pojo.Student;
/**
* <h1></h1>
*
* <p>create: 2022-12-21 21:22</p>
*
* @author youHong.ai
*/
public class UtilTest extends BaseTest {
@Test
public void test() {
TransTestMapper transMapper = Util.getTransMapper(TransTestMapper.class);
Student student = Builder.builder(Student::new)
.with(Student::setName, "王小明")
.with(Student::setAge, 10)
.with(Student::setSex, 1).build();
boolean b = transMapper.insertStudent(student);
System.out.println(b);
System.out.println(Util.commitTransMapper());
}
}

View File

@ -0,0 +1,20 @@
package youhong.ai.pcn.mapper;
import aiyh.utils.annotation.recordset.Insert;
import aiyh.utils.annotation.recordset.SqlMapper;
import youhong.ai.pcn.pojo.Student;
/**
* <h1></h1>
*
* <p>create: 2022-12-21 22:54</p>
*
* @author youHong.ai
*/
@SqlMapper
public interface TransTestMapper {
@Insert("insert into test_trans (name,age,sex) values (#{name},#{age},#{sex})")
boolean insertStudent(Student student);
}

View File

@ -0,0 +1,21 @@
package youhong.ai.pcn.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* <h1></h1>
*
* <p>create: 2022-12-21 22:55</p>
*
* @author youHong.ai
*/
@Getter
@Setter
public class Student {
private int id;
private String name;
private int age;
private int sex;
}