Commit 499b64d856094a1ee11a6f549d5e7f0a13c01a54
0 parents
Exists in
master
and in
2 other branches
first
Showing
12 changed files
with
1457 additions
and
0 deletions
Show diff stats
1 | +++ a/build.gradle | |
... | ... | @@ -0,0 +1,27 @@ |
1 | +/* | |
2 | + * This file was generated by the Gradle 'init' task. | |
3 | + * | |
4 | + * This generated file contains a sample Java Library project to get you started. | |
5 | + * For more details take a look at the Java Libraries chapter in the Gradle | |
6 | + * user guide available at https://docs.gradle.org/4.5.1/userguide/java_library_plugin.html | |
7 | + */ | |
8 | + | |
9 | +plugins { | |
10 | + // Apply the java-library plugin to add support for Java Library | |
11 | + id 'java' | |
12 | + id 'eclipse' | |
13 | + id 'application' | |
14 | +} | |
15 | + | |
16 | +jar.enabled = true | |
17 | +group = 'com.taover.repository' | |
18 | + | |
19 | +dependencies { | |
20 | + compile("org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final") | |
21 | + compile('org.springframework:spring-jdbc:4.3.9.RELEASE') | |
22 | + compile('mysql:mysql-connector-java') | |
23 | +} | |
24 | + | |
25 | +repositories { | |
26 | + jcenter() | |
27 | +} | ... | ... |
No preview for this file type
1 | +++ a/gradlew | |
... | ... | @@ -0,0 +1,172 @@ |
1 | +#!/usr/bin/env sh | |
2 | + | |
3 | +############################################################################## | |
4 | +## | |
5 | +## Gradle start up script for UN*X | |
6 | +## | |
7 | +############################################################################## | |
8 | + | |
9 | +# Attempt to set APP_HOME | |
10 | +# Resolve links: $0 may be a link | |
11 | +PRG="$0" | |
12 | +# Need this for relative symlinks. | |
13 | +while [ -h "$PRG" ] ; do | |
14 | + ls=`ls -ld "$PRG"` | |
15 | + link=`expr "$ls" : '.*-> \(.*\)$'` | |
16 | + if expr "$link" : '/.*' > /dev/null; then | |
17 | + PRG="$link" | |
18 | + else | |
19 | + PRG=`dirname "$PRG"`"/$link" | |
20 | + fi | |
21 | +done | |
22 | +SAVED="`pwd`" | |
23 | +cd "`dirname \"$PRG\"`/" >/dev/null | |
24 | +APP_HOME="`pwd -P`" | |
25 | +cd "$SAVED" >/dev/null | |
26 | + | |
27 | +APP_NAME="Gradle" | |
28 | +APP_BASE_NAME=`basename "$0"` | |
29 | + | |
30 | +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. | |
31 | +DEFAULT_JVM_OPTS="" | |
32 | + | |
33 | +# Use the maximum available, or set MAX_FD != -1 to use that value. | |
34 | +MAX_FD="maximum" | |
35 | + | |
36 | +warn () { | |
37 | + echo "$*" | |
38 | +} | |
39 | + | |
40 | +die () { | |
41 | + echo | |
42 | + echo "$*" | |
43 | + echo | |
44 | + exit 1 | |
45 | +} | |
46 | + | |
47 | +# OS specific support (must be 'true' or 'false'). | |
48 | +cygwin=false | |
49 | +msys=false | |
50 | +darwin=false | |
51 | +nonstop=false | |
52 | +case "`uname`" in | |
53 | + CYGWIN* ) | |
54 | + cygwin=true | |
55 | + ;; | |
56 | + Darwin* ) | |
57 | + darwin=true | |
58 | + ;; | |
59 | + MINGW* ) | |
60 | + msys=true | |
61 | + ;; | |
62 | + NONSTOP* ) | |
63 | + nonstop=true | |
64 | + ;; | |
65 | +esac | |
66 | + | |
67 | +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar | |
68 | + | |
69 | +# Determine the Java command to use to start the JVM. | |
70 | +if [ -n "$JAVA_HOME" ] ; then | |
71 | + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then | |
72 | + # IBM's JDK on AIX uses strange locations for the executables | |
73 | + JAVACMD="$JAVA_HOME/jre/sh/java" | |
74 | + else | |
75 | + JAVACMD="$JAVA_HOME/bin/java" | |
76 | + fi | |
77 | + if [ ! -x "$JAVACMD" ] ; then | |
78 | + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME | |
79 | + | |
80 | +Please set the JAVA_HOME variable in your environment to match the | |
81 | +location of your Java installation." | |
82 | + fi | |
83 | +else | |
84 | + JAVACMD="java" | |
85 | + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. | |
86 | + | |
87 | +Please set the JAVA_HOME variable in your environment to match the | |
88 | +location of your Java installation." | |
89 | +fi | |
90 | + | |
91 | +# Increase the maximum file descriptors if we can. | |
92 | +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then | |
93 | + MAX_FD_LIMIT=`ulimit -H -n` | |
94 | + if [ $? -eq 0 ] ; then | |
95 | + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then | |
96 | + MAX_FD="$MAX_FD_LIMIT" | |
97 | + fi | |
98 | + ulimit -n $MAX_FD | |
99 | + if [ $? -ne 0 ] ; then | |
100 | + warn "Could not set maximum file descriptor limit: $MAX_FD" | |
101 | + fi | |
102 | + else | |
103 | + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" | |
104 | + fi | |
105 | +fi | |
106 | + | |
107 | +# For Darwin, add options to specify how the application appears in the dock | |
108 | +if $darwin; then | |
109 | + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" | |
110 | +fi | |
111 | + | |
112 | +# For Cygwin, switch paths to Windows format before running java | |
113 | +if $cygwin ; then | |
114 | + APP_HOME=`cygpath --path --mixed "$APP_HOME"` | |
115 | + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` | |
116 | + JAVACMD=`cygpath --unix "$JAVACMD"` | |
117 | + | |
118 | + # We build the pattern for arguments to be converted via cygpath | |
119 | + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` | |
120 | + SEP="" | |
121 | + for dir in $ROOTDIRSRAW ; do | |
122 | + ROOTDIRS="$ROOTDIRS$SEP$dir" | |
123 | + SEP="|" | |
124 | + done | |
125 | + OURCYGPATTERN="(^($ROOTDIRS))" | |
126 | + # Add a user-defined pattern to the cygpath arguments | |
127 | + if [ "$GRADLE_CYGPATTERN" != "" ] ; then | |
128 | + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" | |
129 | + fi | |
130 | + # Now convert the arguments - kludge to limit ourselves to /bin/sh | |
131 | + i=0 | |
132 | + for arg in "$@" ; do | |
133 | + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` | |
134 | + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option | |
135 | + | |
136 | + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition | |
137 | + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` | |
138 | + else | |
139 | + eval `echo args$i`="\"$arg\"" | |
140 | + fi | |
141 | + i=$((i+1)) | |
142 | + done | |
143 | + case $i in | |
144 | + (0) set -- ;; | |
145 | + (1) set -- "$args0" ;; | |
146 | + (2) set -- "$args0" "$args1" ;; | |
147 | + (3) set -- "$args0" "$args1" "$args2" ;; | |
148 | + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; | |
149 | + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; | |
150 | + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; | |
151 | + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; | |
152 | + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; | |
153 | + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; | |
154 | + esac | |
155 | +fi | |
156 | + | |
157 | +# Escape application args | |
158 | +save () { | |
159 | + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done | |
160 | + echo " " | |
161 | +} | |
162 | +APP_ARGS=$(save "$@") | |
163 | + | |
164 | +# Collect all arguments for the java command, following the shell quoting and substitution rules | |
165 | +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" | |
166 | + | |
167 | +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong | |
168 | +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then | |
169 | + cd "$(dirname "$0")" | |
170 | +fi | |
171 | + | |
172 | +exec "$JAVACMD" "$@" | ... | ... |
1 | +++ a/gradlew.bat | |
... | ... | @@ -0,0 +1,84 @@ |
1 | +@if "%DEBUG%" == "" @echo off | |
2 | +@rem ########################################################################## | |
3 | +@rem | |
4 | +@rem Gradle startup script for Windows | |
5 | +@rem | |
6 | +@rem ########################################################################## | |
7 | + | |
8 | +@rem Set local scope for the variables with windows NT shell | |
9 | +if "%OS%"=="Windows_NT" setlocal | |
10 | + | |
11 | +set DIRNAME=%~dp0 | |
12 | +if "%DIRNAME%" == "" set DIRNAME=. | |
13 | +set APP_BASE_NAME=%~n0 | |
14 | +set APP_HOME=%DIRNAME% | |
15 | + | |
16 | +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. | |
17 | +set DEFAULT_JVM_OPTS= | |
18 | + | |
19 | +@rem Find java.exe | |
20 | +if defined JAVA_HOME goto findJavaFromJavaHome | |
21 | + | |
22 | +set JAVA_EXE=java.exe | |
23 | +%JAVA_EXE% -version >NUL 2>&1 | |
24 | +if "%ERRORLEVEL%" == "0" goto init | |
25 | + | |
26 | +echo. | |
27 | +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. | |
28 | +echo. | |
29 | +echo Please set the JAVA_HOME variable in your environment to match the | |
30 | +echo location of your Java installation. | |
31 | + | |
32 | +goto fail | |
33 | + | |
34 | +:findJavaFromJavaHome | |
35 | +set JAVA_HOME=%JAVA_HOME:"=% | |
36 | +set JAVA_EXE=%JAVA_HOME%/bin/java.exe | |
37 | + | |
38 | +if exist "%JAVA_EXE%" goto init | |
39 | + | |
40 | +echo. | |
41 | +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% | |
42 | +echo. | |
43 | +echo Please set the JAVA_HOME variable in your environment to match the | |
44 | +echo location of your Java installation. | |
45 | + | |
46 | +goto fail | |
47 | + | |
48 | +:init | |
49 | +@rem Get command-line arguments, handling Windows variants | |
50 | + | |
51 | +if not "%OS%" == "Windows_NT" goto win9xME_args | |
52 | + | |
53 | +:win9xME_args | |
54 | +@rem Slurp the command line arguments. | |
55 | +set CMD_LINE_ARGS= | |
56 | +set _SKIP=2 | |
57 | + | |
58 | +:win9xME_args_slurp | |
59 | +if "x%~1" == "x" goto execute | |
60 | + | |
61 | +set CMD_LINE_ARGS=%* | |
62 | + | |
63 | +:execute | |
64 | +@rem Setup the command line | |
65 | + | |
66 | +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar | |
67 | + | |
68 | +@rem Execute Gradle | |
69 | +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% | |
70 | + | |
71 | +:end | |
72 | +@rem End local scope for the variables with windows NT shell | |
73 | +if "%ERRORLEVEL%"=="0" goto mainEnd | |
74 | + | |
75 | +:fail | |
76 | +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of | |
77 | +rem the _cmd.exe /c_ return code! | |
78 | +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 | |
79 | +exit /b 1 | |
80 | + | |
81 | +:mainEnd | |
82 | +if "%OS%"=="Windows_NT" endlocal | |
83 | + | |
84 | +:omega | ... | ... |
1 | +++ a/settings.gradle | |
... | ... | @@ -0,0 +1,10 @@ |
1 | +/* | |
2 | + * This file was generated by the Gradle 'init' task. | |
3 | + * | |
4 | + * The settings file is used to specify which projects to include in your build. | |
5 | + * | |
6 | + * Detailed information about configuring a multi-project build in Gradle can be found | |
7 | + * in the user guide at https://docs.gradle.org/4.5.1/userguide/multi_project_builds.html | |
8 | + */ | |
9 | + | |
10 | +rootProject.name = 'com-taover-repository' | ... | ... |
src/main/java/com/taover/repository/CustomJdbcTemplate.java
0 → 100644
1 | +++ a/src/main/java/com/taover/repository/CustomJdbcTemplate.java | |
... | ... | @@ -0,0 +1,703 @@ |
1 | +package com.taover.repository; | |
2 | + | |
3 | +import java.io.Serializable; | |
4 | +import java.lang.reflect.Field; | |
5 | +import java.lang.reflect.ParameterizedType; | |
6 | +import java.math.BigInteger; | |
7 | +import java.util.ArrayList; | |
8 | +import java.util.HashMap; | |
9 | +import java.util.Iterator; | |
10 | +import java.util.List; | |
11 | +import java.util.Map; | |
12 | + | |
13 | +import javax.annotation.Resource; | |
14 | +import javax.persistence.Column; | |
15 | +import javax.persistence.Id; | |
16 | +import javax.persistence.Table; | |
17 | + | |
18 | +import org.springframework.jdbc.core.JdbcTemplate; | |
19 | +import org.springframework.util.StringUtils; | |
20 | + | |
21 | +/** | |
22 | + * | |
23 | + * @author root | |
24 | + * | |
25 | + * @param <T> | |
26 | + * @param <ID> | |
27 | + */ | |
28 | +public class CustomJdbcTemplate<T, ID extends Serializable> { | |
29 | + @Resource | |
30 | + private JdbcTemplate jdbcTemplateRead; | |
31 | + @Resource | |
32 | + private JdbcTemplate jdbcTemplateWrite; | |
33 | + | |
34 | + private Map<String, String> beanToTableField; | |
35 | + private Map<String, String> tableToBeanField; | |
36 | + private String tableFieldNameListGapWithComma; | |
37 | + private String idTableFieldName; | |
38 | + private String idBeanFieldName; | |
39 | + private String dbName; | |
40 | + private String tableName; | |
41 | + private Class<T> tClassInfo; | |
42 | + private CustomJdbcTemplateRowMapper customJdbcTemplateRowMapper; | |
43 | + | |
44 | + public CustomJdbcTemplateRowMapper getCustomJdbcTemplateRowMapper(){ | |
45 | + return this.customJdbcTemplateRowMapper; | |
46 | + } | |
47 | + | |
48 | + public CustomJdbcTemplate() throws Exception{ | |
49 | + //获取泛型类Class | |
50 | + this.tClassInfo = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; | |
51 | + | |
52 | + //检查实体声明 | |
53 | + Table annoTable = (Table) tClassInfo.getAnnotation(Table.class); | |
54 | + if(annoTable == null){ | |
55 | + throw new Exception("DAO层初始化失败,失败原因:"+tClassInfo.getName()+"实体类,没有@Table注解指定表名"); | |
56 | + } | |
57 | + this.tableName = annoTable.name(); | |
58 | + if(annoTable.schema() != null){ | |
59 | + this.dbName = annoTable.schema(); | |
60 | + }else if(annoTable.catalog() != null){ | |
61 | + this.dbName = annoTable.catalog(); | |
62 | + } | |
63 | + | |
64 | + //初始化数据 | |
65 | + beanToTableField = new HashMap<String, String>(); | |
66 | + tableToBeanField = new HashMap<String, String>(); | |
67 | + tableFieldNameListGapWithComma = ""; | |
68 | + Field[] declaredFields = tClassInfo.getDeclaredFields(); | |
69 | + for(int i=0; i<declaredFields.length; ++i){ | |
70 | + Field currField = declaredFields[i]; | |
71 | + String fieldName = currField.getName(); | |
72 | + Id annoId = (Id)currField.getAnnotation(Id.class); | |
73 | + Column annoColumn = (Column)currField.getAnnotation(Column.class); | |
74 | + if(annoId != null){ | |
75 | + if(annoColumn == null){ | |
76 | + idTableFieldName = this.camelToUnderline(fieldName); | |
77 | + }else{ | |
78 | + idTableFieldName = annoColumn.name(); | |
79 | + } | |
80 | + idBeanFieldName = fieldName; | |
81 | + tableFieldNameListGapWithComma += idTableFieldName+","; | |
82 | + beanToTableField.put(fieldName, idTableFieldName); | |
83 | + tableToBeanField.put(idTableFieldName, fieldName); | |
84 | + }else{ | |
85 | + if(annoColumn != null){ | |
86 | + String tableFieldName = annoColumn.name(); | |
87 | + tableFieldNameListGapWithComma += tableFieldName+","; | |
88 | + beanToTableField.put(fieldName, tableFieldName); | |
89 | + tableToBeanField.put(tableFieldName, fieldName); | |
90 | + } | |
91 | + } | |
92 | + } | |
93 | + | |
94 | + //检验是否有属性 | |
95 | + if(beanToTableField.isEmpty()){ | |
96 | + throw new Exception("DAO层初始化失败,失败原因:"+this.tClassInfo.getName()+"实体类,没有在实体中找到属性信息"); | |
97 | + } | |
98 | + | |
99 | + //去除逗号 | |
100 | + tableFieldNameListGapWithComma = tableFieldNameListGapWithComma.substring(0, tableFieldNameListGapWithComma.length()-1); | |
101 | + | |
102 | + //创建rowmapper | |
103 | + this.customJdbcTemplateRowMapper = new CustomJdbcTemplateRowMapper(this.tClassInfo, this.tableToBeanField); | |
104 | + } | |
105 | + | |
106 | + /** | |
107 | + * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br> | |
108 | + * 例如:HelloWorld->HELLO_WORLD | |
109 | + * @param name 转换前的驼峰式命名的字符串 | |
110 | + * @return 转换后下划线大写方式命名的字符串 | |
111 | + */ | |
112 | + public String camelToUnderline(String name) { | |
113 | + StringBuilder result = new StringBuilder(); | |
114 | + if (name != null && name.length() > 0) { | |
115 | + // 将第一个字符处理成大写 | |
116 | + result.append(name.substring(0, 1).toUpperCase()); | |
117 | + // 循环处理其余字符 | |
118 | + for (int i = 1; i < name.length(); i++) { | |
119 | + String s = name.substring(i, i + 1); | |
120 | + // 在大写字母前添加下划线 | |
121 | + if (Character.isUpperCase(s.charAt(0)) && Character.isLetter(s.charAt(0))) { | |
122 | + result.append("_"); | |
123 | + } | |
124 | + // 其他字符直接转成大写 | |
125 | + result.append(s.toUpperCase()); | |
126 | + } | |
127 | + } | |
128 | + return result.toString(); | |
129 | + } | |
130 | + | |
131 | + /** | |
132 | + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br> | |
133 | + * 例如:HELLO_WORLD->HelloWorld | |
134 | + * @param name 转换前的下划线大写方式命名的字符串 | |
135 | + * @return 转换后的驼峰式命名的字符串 | |
136 | + */ | |
137 | + public String underlineToCamel(String name) { | |
138 | + StringBuilder result = new StringBuilder(); | |
139 | + // 快速检查 | |
140 | + if (name == null || name.isEmpty()) { | |
141 | + // 没必要转换 | |
142 | + return ""; | |
143 | + } else if (!name.contains("_")) { | |
144 | + // 不含下划线,仅将首字母小写 | |
145 | + return name.substring(0, 1).toLowerCase() + name.substring(1); | |
146 | + } | |
147 | + // 用下划线将原始字符串分割 | |
148 | + String camels[] = name.split("_"); | |
149 | + for (String camel : camels) { | |
150 | + // 跳过原始字符串中开头、结尾的下换线或双重下划线 | |
151 | + if (camel.isEmpty()) { | |
152 | + continue; | |
153 | + } | |
154 | + // 处理真正的驼峰片段 | |
155 | + if (result.length() == 0) { | |
156 | + // 第一个驼峰片段,全部字母都小写 | |
157 | + result.append(camel.toLowerCase()); | |
158 | + } else { | |
159 | + // 其他的驼峰片段,首字母大写 | |
160 | + result.append(camel.substring(0, 1).toUpperCase()); | |
161 | + result.append(camel.substring(1).toLowerCase()); | |
162 | + } | |
163 | + } | |
164 | + return result.toString(); | |
165 | + } | |
166 | + | |
167 | + public void appendWhereCondition(StringBuffer sql, StringBuffer pql, List<Object> list, List<Object[]> condition) { | |
168 | + if (condition == null || condition.size() == 0) return; | |
169 | + Object[] con = condition.get(0); | |
170 | + int iLen = condition.size(); | |
171 | + sql.append(" WHERE "); | |
172 | + pql.append(" WHERE "); | |
173 | + sql.append(con[0]); | |
174 | + pql.append(con[0]); | |
175 | + if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { | |
176 | + sql.append(" " + con[1] + " ?"); | |
177 | + pql.append(" " + con[1] + " " + con[2]); | |
178 | + list.add(con[2]); | |
179 | + } | |
180 | + for (int i = 1; i < iLen; i++) { | |
181 | + con = condition.get(i); | |
182 | + sql.append(" AND "); | |
183 | + pql.append(" AND "); | |
184 | + sql.append(con[0]); | |
185 | + pql.append(con[0]); | |
186 | + if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; | |
187 | + sql.append(" " + con[1] + " ?"); | |
188 | + pql.append(" " + con[1] + " " + con[2]); | |
189 | + list.add(con[2]); | |
190 | + } | |
191 | + } | |
192 | + | |
193 | + public void appendWhereConditionForCount(StringBuffer sql, List<Object[]> condition) { | |
194 | + if (condition == null || condition.size() == 0) return; | |
195 | + Object[] con = condition.get(0); | |
196 | + int iLen = condition.size(); | |
197 | + sql.append(" WHERE "); | |
198 | + sql.append(con[0]); | |
199 | + if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { | |
200 | + sql.append(" " + con[1] + " ?"); | |
201 | + } | |
202 | + for (int i = 1; i < iLen; i++) { | |
203 | + con = condition.get(i); | |
204 | + sql.append(" AND "); | |
205 | + sql.append(con[0]); | |
206 | + if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; | |
207 | + sql.append(" " + con[1] + " ?"); | |
208 | + } | |
209 | + } | |
210 | + | |
211 | + public void appendSql(StringBuffer sql, StringBuffer pql, List<Object> list, List<Object[]> obj) { | |
212 | + for (Object[] arg : obj) { | |
213 | + String opt = "="; | |
214 | + if (arg.length > 2) { | |
215 | + opt = (String)arg[2]; | |
216 | + } | |
217 | + if (opt.equals("=")) { | |
218 | + sql.append(" " + arg[0] + " = ?,"); | |
219 | + pql.append(" " + arg[0] + " = " + arg[1] + ","); | |
220 | + } else { | |
221 | + sql.append(" " + arg[0] + " = " + arg[0] + " + ?,"); | |
222 | + pql.append(" " + arg[0] + " = " + arg[0] + " + " + arg[1] + ","); | |
223 | + } | |
224 | + list.add(arg[1]); | |
225 | + } | |
226 | + } | |
227 | + | |
228 | + private String getTableSql(){ | |
229 | + return "".equals(this.dbName)?"`"+this.tableName+"`":("`"+this.dbName+"`.`"+this.tableName+"`"); | |
230 | + } | |
231 | + | |
232 | + /** | |
233 | + * 按主键查询 | |
234 | + */ | |
235 | + public T findEntityByID(ID id) { | |
236 | + return findEntityByID(id, true, false); | |
237 | + } | |
238 | + | |
239 | + /** | |
240 | + * 按主键查询 | |
241 | + * isLock 是否锁定, 默认不锁 | |
242 | + * fromWriteDB 是否从写库读写,默认从读库查询 | |
243 | + */ | |
244 | + public T findEntityByID(ID id, boolean fromWriteDB, boolean isLock) { | |
245 | + StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); | |
246 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
247 | + sql.append(" WHERE "+idTableFieldName+" = ?"); | |
248 | + pql.append(" WHERE "+idTableFieldName+" = " + id); | |
249 | + if (isLock) { | |
250 | + sql.append(" FOR UPDATE"); | |
251 | + pql.append(" FOR UPDATE"); | |
252 | + } | |
253 | + T result = null; | |
254 | + try { | |
255 | + result = (T) (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForObject(sql.toString(), this.customJdbcTemplateRowMapper, id); | |
256 | + }catch(Exception e) { | |
257 | + UtilsLog.errorForException(e, this.getClass()); | |
258 | + } | |
259 | + return result; | |
260 | + } | |
261 | + | |
262 | + /** | |
263 | + * 根据条件List<Object[]>查询 | |
264 | + * Object[]数组长度是3 | |
265 | + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
266 | + */ | |
267 | + public T findEntityByCondition(List<Object[]> condition) throws Exception { | |
268 | + List<T> tempList = findListByCondition(condition, null, false); | |
269 | + if(tempList == null || tempList.size() == 0){ | |
270 | + return null; | |
271 | + } | |
272 | + if(tempList != null && tempList.size() == 1){ | |
273 | + return tempList.get(0); | |
274 | + }else{ | |
275 | + throw new Exception("数据库存在多条记录满足条件"); | |
276 | + } | |
277 | + } | |
278 | + | |
279 | + /** | |
280 | + * 根据条件sql查询 | |
281 | + * sqlCondition 为where 后面的条件。 | |
282 | + */ | |
283 | + public T findEntityBySql(String sqlCondition) throws Exception{ | |
284 | + List<T> tempList = findListBySql(sqlCondition, false); | |
285 | + if(tempList == null || tempList.size() == 0){ | |
286 | + return null; | |
287 | + } | |
288 | + if(tempList != null && tempList.size() == 1){ | |
289 | + return tempList.get(0); | |
290 | + }else{ | |
291 | + throw new Exception("数据库存在多条记录满足条件"); | |
292 | + } | |
293 | + } | |
294 | + | |
295 | + /** | |
296 | + * 根据条件List<Object[]>查询 | |
297 | + * Object[]数组长度是3 | |
298 | + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
299 | + */ | |
300 | + public List<T> findListByCondition(List<Object[]> condition) { | |
301 | + return findListByCondition(condition,null, false); | |
302 | + } | |
303 | + | |
304 | + /** | |
305 | + * 根据条件List<Object[]>查询 | |
306 | + * Object[]数组长度是3 | |
307 | + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
308 | + */ | |
309 | + public List<T> findListByCondition(List<Object[]> condition, String sortCondition, boolean fromWriteDB) { | |
310 | + StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); | |
311 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
312 | + List<Object> list = new ArrayList<Object>(); | |
313 | + this.appendWhereCondition(sql, pql, list, condition); | |
314 | + if(!StringUtils.isEmpty(sortCondition)){ | |
315 | + sql.append(" " + sortCondition + " "); | |
316 | + pql.append(" " + sortCondition + " "); | |
317 | + } | |
318 | + List<T> resultList = null; | |
319 | + try { | |
320 | + resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), this.customJdbcTemplateRowMapper, list.toArray()); | |
321 | + return resultList; | |
322 | + } catch (Exception e) { | |
323 | + UtilsLog.errorForException(e, this.getClass()); | |
324 | + } | |
325 | + return null; | |
326 | + } | |
327 | + | |
328 | + /** | |
329 | + * 根据条件sql查询 | |
330 | + * sqlCondition 为where 后面的条件。 | |
331 | + */ | |
332 | + public List<T> findListBySql(String sqlCondition) { | |
333 | + return findListBySql(sqlCondition, false); | |
334 | + } | |
335 | + | |
336 | + /** | |
337 | + * 根据条件sql查询 | |
338 | + * sqlCondition 为where 后面的条件。 | |
339 | + */ | |
340 | + public List<T> findListBySql(String sqlCondition, boolean fromWriteDB) { | |
341 | + StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition); | |
342 | + List<T> resultList = null; | |
343 | + try { | |
344 | + resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), this.customJdbcTemplateRowMapper); | |
345 | + return resultList; | |
346 | + } catch (Exception e) { | |
347 | + UtilsLog.errorForException(e, this.getClass()); | |
348 | + } | |
349 | + return null; | |
350 | + } | |
351 | + | |
352 | + /** | |
353 | + * 按条件分页查询 | |
354 | + * Object[]数组长度是3 | |
355 | + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
356 | + */ | |
357 | + public Map<String, Object> findPageByCondition(List<Object[]> condition,int page, int pageSize) { | |
358 | + return findPageByCondition(condition, null , page, pageSize, false); | |
359 | + } | |
360 | + | |
361 | + /** | |
362 | + * 按条件分页查询 | |
363 | + * Object[]数组长度是3 | |
364 | + * Object[]第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
365 | + * boolean isUseCache, 是否用缓存,默认用。 | |
366 | + * boolean isAddCache, 是否添加缓存,默认添加。 | |
367 | + */ | |
368 | + public Map<String, Object> findPageByCondition(List<Object[]> condition,String sortCondition, int page, int pageSize, boolean fromWriteDB) { | |
369 | + StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); | |
370 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
371 | + StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) rowCount FROM "+this.getTableSql()); | |
372 | + | |
373 | + List<Object> count_list = new ArrayList<Object>(); | |
374 | + List<Object> page_list = new ArrayList<Object>(); | |
375 | + this.appendWhereConditionForCount(sqlCount, condition); | |
376 | + this.appendWhereCondition(sql, pql, count_list, condition); | |
377 | + for (int i = 0; i < count_list.size(); i++) | |
378 | + page_list.add(count_list.get(i)); | |
379 | + | |
380 | + page_list.add((page - 1) * pageSize); | |
381 | + page_list.add(pageSize); | |
382 | + | |
383 | + if(!StringUtils.isEmpty(sortCondition)){ | |
384 | + sql.append(" " + sortCondition + " "); | |
385 | + pql.append(" " + sortCondition + " "); | |
386 | + } | |
387 | + | |
388 | + String pageSql = sql.toString() + " limit ?, ?"; | |
389 | + | |
390 | + List<T> resultList = null; | |
391 | + try { | |
392 | + Map<String, Object> totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString(), count_list.toArray()) ; | |
393 | + | |
394 | + Map<String, Object> resultMap = new HashMap<String, Object>(); | |
395 | + resultMap.put("page", page); | |
396 | + resultMap.put("total", totalRowsMap.get("rowCount")); | |
397 | + resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), this.customJdbcTemplateRowMapper, page_list.toArray()); | |
398 | + resultMap.put("rows", resultList); | |
399 | + return resultMap; | |
400 | + } catch (Exception e) { | |
401 | + UtilsLog.errorForException(e, this.getClass()); | |
402 | + } | |
403 | + return null; | |
404 | + } | |
405 | + | |
406 | + /** | |
407 | + * 按sql分页查询, sqlCondition为where 后条件sql | |
408 | + */ | |
409 | + public Map<String, Object> findPageBySql(String sqlCondition, int page, int pageSize) { | |
410 | + return findPageBySql(sqlCondition, page, pageSize, false); | |
411 | + } | |
412 | + | |
413 | + /** | |
414 | + * 按sql分页查询, sqlCondition为where 后条件sql | |
415 | + */ | |
416 | + public Map<String, Object> findPageBySql(String sqlCondition, int page, int pageSize,boolean fromWriteDB) { | |
417 | + StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition ); | |
418 | + StringBuffer sqlCount = new StringBuffer("SELECT count(1) rowCount FROM "+this.getTableSql()+" WHERE " + sqlCondition); | |
419 | + String pageSql = sql.toString() + " limit ?, ?"; | |
420 | + String pagePql = sql.toString() + " limit " + ((page -1) * pageSize) + ", " + (page * pageSize); | |
421 | + List<Object> page_list = new ArrayList<Object>(); | |
422 | + page_list.add((page - 1) * pageSize); | |
423 | + page_list.add(page * pageSize); | |
424 | + | |
425 | + | |
426 | + List<T> resultList = null; | |
427 | + try { | |
428 | + | |
429 | + Map<String, Object> totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString()); | |
430 | + | |
431 | + Map<String, Object> resultMap = new HashMap<String, Object>(); | |
432 | + resultMap.put("page", page); | |
433 | + resultMap.put("total", totalRowsMap.get("rowCount")); | |
434 | + resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), this.customJdbcTemplateRowMapper, page_list.toArray()); | |
435 | + resultMap.put("rows", resultList); | |
436 | + return resultMap; | |
437 | + } catch (Exception e) { | |
438 | + UtilsLog.errorForException(e, this.getClass()); | |
439 | + } | |
440 | + return null; | |
441 | + } | |
442 | + | |
443 | + /** | |
444 | + * 添加 | |
445 | + */ | |
446 | + public BigInteger addEntityForAutoincrementId(T entity) { | |
447 | + StringBuffer sqlForLog = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); | |
448 | + StringBuffer sqlValueForLog = new StringBuffer(") VALUES ("); | |
449 | + StringBuffer sqlInsertPart = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); | |
450 | + StringBuffer sqlColumnPart = new StringBuffer(") VALUES ("); | |
451 | + List<Object> paramList = new ArrayList<Object>(); | |
452 | + | |
453 | + Iterator<String> beanFieldIter = this.beanToTableField.keySet().iterator(); | |
454 | + while(beanFieldIter.hasNext()){ | |
455 | + String beanFieldName = beanFieldIter.next(); | |
456 | + String tableFieldName = this.beanToTableField.get(beanFieldName); | |
457 | + Field beanField; | |
458 | + Object beanFieldValue = null; | |
459 | + try { | |
460 | + beanField = this.tClassInfo.getDeclaredField(beanFieldName); | |
461 | + beanField.setAccessible(true); | |
462 | + beanFieldValue = beanField.get(entity); | |
463 | + } catch (Exception e) { | |
464 | + e.printStackTrace(); | |
465 | + } | |
466 | + | |
467 | + if(tableFieldName == null || beanFieldName == null || beanFieldValue == null){ | |
468 | + continue; | |
469 | + } | |
470 | + | |
471 | + sqlForLog.append("`"+tableFieldName+"`,"); | |
472 | + sqlValueForLog.append(beanFieldValue.toString()+","); | |
473 | + sqlInsertPart.append("`"+tableFieldName+"`,"); | |
474 | + sqlColumnPart.append(" ?,"); | |
475 | + paramList.add(beanFieldValue); | |
476 | + } | |
477 | + //打印日志内容 | |
478 | + sqlForLog.substring(0, sqlForLog.length()-1); | |
479 | + sqlForLog.append(") VALUES ("); | |
480 | + sqlForLog.append(sqlValueForLog+")"); | |
481 | + //UtilsLog.infoForMessage(sqlForLog.toString(), this.getClass()); | |
482 | + | |
483 | + //执行SQL | |
484 | + String exeSql = sqlInsertPart.substring(0, sqlInsertPart.length()-1)+sqlColumnPart.substring(0, sqlColumnPart.length()-1)+")"; | |
485 | + try { | |
486 | + jdbcTemplateWrite.update(exeSql, paramList.toArray()); | |
487 | + Map<String, Object> lastInsertIdMap = jdbcTemplateWrite.queryForMap("SELECT LAST_INSERT_ID() lastInsertId"); | |
488 | + return (BigInteger)lastInsertIdMap.get("lastInsertId"); | |
489 | + } catch (Exception e) { | |
490 | + UtilsLog.errorForException(e, this.getClass()); | |
491 | + } | |
492 | + return null; | |
493 | + } | |
494 | + | |
495 | + /** | |
496 | + * 批量添加 | |
497 | + */ | |
498 | + public List<BigInteger> addEntityList(List<T> entityList) { | |
499 | + List<BigInteger> result = new ArrayList<BigInteger>(); | |
500 | + for (T entity : entityList) { | |
501 | + result.add(addEntityForAutoincrementId(entity)); | |
502 | + } | |
503 | + return result; | |
504 | + } | |
505 | + | |
506 | + /** | |
507 | + * 按ID删除 | |
508 | + */ | |
509 | + public int deleteEntityByID(ID id) { | |
510 | + StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+" WHERE"); | |
511 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
512 | + pql.append(" "+this.idTableFieldName+" = " + id); | |
513 | + sql.append(" "+this.idTableFieldName+" = ?"); | |
514 | + //UtilsLog.infoForMessage(pql.toString(), this.getClass()); | |
515 | + return jdbcTemplateWrite.update(sql.toString(), id); | |
516 | + } | |
517 | + /** | |
518 | + * 删除按List<Object[]>条件 | |
519 | + * Object[]数组长度是3 | |
520 | + * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
521 | + */ | |
522 | + public int deleteEntityByCondition(List<Object[]> condition) throws Exception{ | |
523 | + if (null == condition || condition.size() == 0) { | |
524 | + throw new Exception("没有传入条件,请至少传入一个筛选条件"); | |
525 | + } | |
526 | + | |
527 | + List<Object> list = new ArrayList<Object>(); | |
528 | + StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+""); | |
529 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
530 | + this.appendWhereCondition(sql, pql, list, condition); | |
531 | + try { | |
532 | + return jdbcTemplateWrite.update( sql.toString(), list.toArray()); | |
533 | + } catch (Exception e) { | |
534 | + UtilsLog.errorForException(e, this.getClass()); | |
535 | + } | |
536 | + return 0; | |
537 | + } | |
538 | + | |
539 | + /** | |
540 | + * 删除按condition条件 | |
541 | + * 建议使用deleteTByCondition(List<Object[]> condition), 如果removeTByCondition(List<Object[]> condition)满足不了where条件可以使用此方法。 | |
542 | + * condition为where后面的条件,condition不能为空。 | |
543 | + */ | |
544 | + public int deleteEntityBySql(String sqlCondition) throws Exception{ | |
545 | + if("".equals(sqlCondition)) { | |
546 | + throw new Exception("没有传入条件,请至少传入一个筛选条件"); | |
547 | + } | |
548 | + StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+" WHERE "); | |
549 | + try { | |
550 | + return jdbcTemplateWrite.update( sql.toString() + sqlCondition); | |
551 | + } catch (Exception e) { | |
552 | + UtilsLog.errorForException(e, this.getClass()); | |
553 | + } | |
554 | + return 0; | |
555 | + } | |
556 | + | |
557 | + /** | |
558 | + * 根据list对象逐个删除。 | |
559 | + */ | |
560 | + public List<Integer> deleteEntityList(List<T> entityList) { | |
561 | + List<Integer> result = new ArrayList<Integer>(); | |
562 | + for (T entity : entityList) { | |
563 | + Field beanField; | |
564 | + Object beanFieldValue = Integer.valueOf(0); | |
565 | + try { | |
566 | + beanField = this.tClassInfo.getDeclaredField(this.idBeanFieldName); | |
567 | + beanField.setAccessible(true); | |
568 | + beanFieldValue = beanField.get(entity); | |
569 | + } catch (Exception e) { | |
570 | + UtilsLog.errorForException(e, this.getClass()); | |
571 | + } | |
572 | + result.add(deleteEntityByID((ID)beanFieldValue)); | |
573 | + } | |
574 | + return result; | |
575 | + } | |
576 | + | |
577 | + /** | |
578 | + * 根据ID修改指定的值 | |
579 | + */ | |
580 | + public int updateEntityById(List<Object[]> changeList, ID id) throws Exception{ | |
581 | + if(null == id){ | |
582 | + throw new Exception("请求条件异常,没有传入主键ID!"); | |
583 | + } | |
584 | + | |
585 | + StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); | |
586 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
587 | + List<Object> list = new ArrayList<Object>(); | |
588 | + for (int i = 0, iLen = changeList.size(); i < iLen; i++) { | |
589 | + String name = (String) changeList.get(i)[0]; | |
590 | + Object value = changeList.get(i)[1]; | |
591 | + String variationOpt = "="; | |
592 | + if (changeList.get(i).length > 2) | |
593 | + variationOpt = (String)changeList.get(i)[2]; | |
594 | + if (variationOpt.equals("=")) { | |
595 | + sql.append(" " + name + " = ?,"); | |
596 | + list.add(value); | |
597 | + if (value == null) { | |
598 | + pql.append(" " + name + "=null,"); | |
599 | + } else { | |
600 | + pql.append(" " + name + "=\"" + value.toString() + "\","); | |
601 | + } | |
602 | + } else { | |
603 | + sql.append(" " + name + " = " + name + " + ?,"); | |
604 | + list.add(value); | |
605 | + pql.append(" " + name + " = " + name + " + " + value.toString() + ","); | |
606 | + } | |
607 | + } | |
608 | + | |
609 | + //记录SQL | |
610 | + String pwhere = " WHERE "+this.idTableFieldName+"=\"" + id + "\""; | |
611 | + //UtilsLog.infoForMessage(pql.toString()+pwhere, this.getClass()); | |
612 | + | |
613 | + try { | |
614 | + String where = " WHERE "+this.idTableFieldName+"=?"; | |
615 | + String updateSql = sql.substring(0, sql.length()-1)+where; | |
616 | + list.add(id); | |
617 | + return jdbcTemplateWrite.update(updateSql, list.toArray()); | |
618 | + } catch (Exception e) { | |
619 | + UtilsLog.errorForException(e, this.getClass()); | |
620 | + } | |
621 | + return 0; | |
622 | + } | |
623 | + | |
624 | + /** | |
625 | + * List<Object[]> updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 | |
626 | + * List<Object[]> condition 修改的条件, 数组长度是3, 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 | |
627 | + */ | |
628 | + public int updateEntityByCondition(List<Object[]> updateObj, List<Object[]> condition) throws Exception{ | |
629 | + if (null == updateObj || updateObj.size() == 0) { | |
630 | + throw new Exception("请求条件异常,请求条件List<Object[]> updateObj不能为空!"); | |
631 | + } | |
632 | + if (null == condition || condition.size() == 0) { | |
633 | + throw new Exception("请求条件异常,请求条件List<Object[]> condition不能为空!"); | |
634 | + } | |
635 | + | |
636 | + StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); | |
637 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
638 | + List<Object> list = new ArrayList<Object>(); | |
639 | + this.appendSql(sql, pql, list, updateObj); | |
640 | + | |
641 | + StringBuffer where = new StringBuffer(""); | |
642 | + StringBuffer pwhere = new StringBuffer(""); | |
643 | + this.appendWhereCondition(where, pwhere, list, condition); | |
644 | + | |
645 | + //UtilsLog.infoForMessage(pql.toString()+pwhere.toString(), this.getClass()); | |
646 | + | |
647 | + String updateSql = sql.substring(0, sql.length()-1)+where.toString(); | |
648 | + try { | |
649 | + return jdbcTemplateWrite.update(updateSql, list.toArray()); | |
650 | + } catch (Exception e) { | |
651 | + UtilsLog.errorForException(e, this.getClass()); | |
652 | + } | |
653 | + return 0; | |
654 | + } | |
655 | + | |
656 | + /** | |
657 | + * List<Object[]> updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 | |
658 | + * String sqlCondition 修改的条件。 | |
659 | + */ | |
660 | + public int updateEntityBySql(List<Object[]> updateObj, String sqlCondition) throws Exception{ | |
661 | + if (null == updateObj || updateObj.size() == 0) { | |
662 | + throw new Exception("请求条件异常,请求条件List<Object[]> updateObj不能为空!"); | |
663 | + } | |
664 | + if ("".equals(sqlCondition)) { | |
665 | + throw new Exception("请求条件异常,请求条件sqlCondition不能为空!"); | |
666 | + } | |
667 | + | |
668 | + StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); | |
669 | + StringBuffer pql = new StringBuffer(sql.toString()); | |
670 | + List<Object> list = new ArrayList<Object>(); | |
671 | + this.appendSql(sql, pql, list, updateObj); | |
672 | + | |
673 | + try { | |
674 | + String updateSql = sql.toString().substring(0, sql.length()-1) + " WHERE "+sqlCondition; | |
675 | + return jdbcTemplateWrite.update(updateSql, list.toArray()); | |
676 | + } catch (Exception e) { | |
677 | + UtilsLog.errorForException(e, this.getClass()); | |
678 | + } | |
679 | + return 0; | |
680 | + } | |
681 | + | |
682 | + public Map<String, Object> getPageData(String coreSql, String orderByPartSql, Integer page, Integer pageSize){ | |
683 | + //构造查询语句 | |
684 | + String querySql = coreSql+orderByPartSql+UtilsSql.getLimitCondition(page, pageSize); | |
685 | + | |
686 | + //构造统计计数语句 | |
687 | + String countSql = "select count(*) rows from ("+coreSql+" ) t "; | |
688 | + | |
689 | + //执行查询 | |
690 | + List<Map<String, Object>> queryData = new ArrayList<Map<String, Object>>(); | |
691 | + Map<String, Object> countData = new HashMap<String, Object>(); | |
692 | + try{ | |
693 | + queryData = this.jdbcTemplateRead.queryForList(querySql); | |
694 | + countData = this.jdbcTemplateRead.queryForMap(countSql); | |
695 | + }catch(Exception e){ | |
696 | + countData.put("rows", "0"); | |
697 | + | |
698 | + UtilsLog.errorForException(e, this.getClass()); | |
699 | + } | |
700 | + | |
701 | + return UtilsSql.createPage(page, Integer.valueOf(countData.get("rows").toString()), queryData); | |
702 | + } | |
703 | +} | ... | ... |
src/main/java/com/taover/repository/CustomJdbcTemplateRowMapper.java
0 → 100644
1 | +++ a/src/main/java/com/taover/repository/CustomJdbcTemplateRowMapper.java | |
... | ... | @@ -0,0 +1,47 @@ |
1 | +package com.taover.repository; | |
2 | + | |
3 | +import java.lang.reflect.Field; | |
4 | +import java.sql.ResultSet; | |
5 | +import java.sql.SQLException; | |
6 | +import java.util.Map; | |
7 | + | |
8 | +import org.springframework.jdbc.core.RowMapper; | |
9 | +import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetMetaData; | |
10 | + | |
11 | +public class CustomJdbcTemplateRowMapper implements RowMapper{ | |
12 | + private Class classInfo; | |
13 | + private Map<String, String> tableToBeanMap; | |
14 | + | |
15 | + public CustomJdbcTemplateRowMapper(Class classInfo, Map<String, String> tableToBeanMap) { | |
16 | + this.classInfo = classInfo; | |
17 | + this.tableToBeanMap = tableToBeanMap; | |
18 | + } | |
19 | + | |
20 | + @Override | |
21 | + public Object mapRow(ResultSet rs, int index) throws SQLException { | |
22 | + Object targetObj; | |
23 | + try { | |
24 | + targetObj = this.classInfo.newInstance(); | |
25 | + } catch (Exception e) { | |
26 | + throw new RuntimeException(e); | |
27 | + } | |
28 | + | |
29 | + ResultSetWrappingSqlRowSetMetaData wapping = new ResultSetWrappingSqlRowSetMetaData(rs.getMetaData()); | |
30 | + int columnCount = wapping.getColumnCount(); | |
31 | + for (int i = 1; i<=columnCount; i++) { | |
32 | + String tableFieldName = wapping.getColumnLabel(i); | |
33 | + String beanFieldName = this.tableToBeanMap.get(tableFieldName); | |
34 | + Object value = rs.getObject(i); | |
35 | + try { | |
36 | + if(null != value && beanFieldName != null){ | |
37 | + Field beanField = this.classInfo.getDeclaredField(beanFieldName); | |
38 | + beanField.setAccessible(true); | |
39 | + beanField.set(targetObj, value); | |
40 | + } | |
41 | + } catch (Exception e) { | |
42 | + e.printStackTrace(); | |
43 | + } | |
44 | + } | |
45 | + return targetObj; | |
46 | + } | |
47 | +} | ... | ... |
1 | +++ a/src/main/java/com/taover/repository/UtilsLog.java | |
... | ... | @@ -0,0 +1,74 @@ |
1 | +package com.taover.repository; | |
2 | + | |
3 | +import java.io.PrintWriter; | |
4 | +import java.io.StringWriter; | |
5 | +import java.util.HashMap; | |
6 | +import java.util.Map; | |
7 | + | |
8 | +import org.apache.commons.logging.Log; | |
9 | +import org.apache.commons.logging.LogFactory; | |
10 | + | |
11 | + | |
12 | +public class UtilsLog { | |
13 | + private static Map<String, Log> logByClassName = new HashMap<String, Log>(); | |
14 | + | |
15 | + /** | |
16 | + * 输出日志文本 | |
17 | + * @param message | |
18 | + * @param infoClass | |
19 | + */ | |
20 | + public static void infoForMessage(String message, Class infoClass){ | |
21 | + String className = infoClass.getName(); | |
22 | + Log log = logByClassName.get(infoClass.getName()); | |
23 | + if(log == null){ | |
24 | + log = LogFactory.getLog(infoClass); | |
25 | + if(log == null){ | |
26 | + return; | |
27 | + } | |
28 | + logByClassName.put(className, log); | |
29 | + } | |
30 | + log.info(message); | |
31 | + } | |
32 | + | |
33 | + /** | |
34 | + * 输出日志Exception内容 | |
35 | + * @param e | |
36 | + * @param infoClass | |
37 | + */ | |
38 | + public static String infoForException(Exception e, Class infoClass){ | |
39 | + StringWriter sw = new StringWriter(); | |
40 | + e.printStackTrace(new PrintWriter(sw)); | |
41 | + UtilsLog.infoForMessage(sw.toString(), infoClass); | |
42 | + return sw.toString(); | |
43 | + } | |
44 | + | |
45 | + /** | |
46 | + * 输出文本内容 | |
47 | + * @param message | |
48 | + * @param infoClass | |
49 | + */ | |
50 | + public static void errorForMessage(String message, Class infoClass){ | |
51 | + String className = infoClass.getName(); | |
52 | + Log log = logByClassName.get(infoClass.getName()); | |
53 | + if(log == null){ | |
54 | + log = LogFactory.getLog(infoClass); | |
55 | + if(log == null){ | |
56 | + return; | |
57 | + } | |
58 | + logByClassName.put(className, log); | |
59 | + } | |
60 | + log.error(message); | |
61 | + } | |
62 | + | |
63 | + /** | |
64 | + * 输出日志Exception信息 | |
65 | + * @param e | |
66 | + * @param infoClass | |
67 | + */ | |
68 | + public static String errorForException(Exception e, Class infoClass){ | |
69 | + StringWriter sw = new StringWriter(); | |
70 | + e.printStackTrace(new PrintWriter(sw)); | |
71 | + UtilsLog.errorForMessage(sw.toString(), infoClass); | |
72 | + return sw.toString(); | |
73 | + } | |
74 | +} | ... | ... |
1 | +++ a/src/main/java/com/taover/repository/UtilsSql.java | |
... | ... | @@ -0,0 +1,86 @@ |
1 | +package com.taover.repository; | |
2 | + | |
3 | +import java.util.HashMap; | |
4 | +import java.util.Map; | |
5 | + | |
6 | +import org.springframework.util.StringUtils; | |
7 | + | |
8 | +public class UtilsSql { | |
9 | + | |
10 | + /** | |
11 | + * 获取排序字符串 | |
12 | + * @param sort | |
13 | + * @param order | |
14 | + * @param columnPreffix | |
15 | + * @return | |
16 | + */ | |
17 | + public static String getSortCondition(String sort, String order, String columnPreffix){ | |
18 | + String underScoreSort = UtilsString.underscoreName(sort).toLowerCase(); | |
19 | + if(StringUtils.isEmpty(columnPreffix)){ | |
20 | + columnPreffix = ""; | |
21 | + } | |
22 | + String sortCondition = " "; | |
23 | + if(!StringUtils.isEmpty(underScoreSort)){ | |
24 | + sortCondition = " order by "; | |
25 | + String[] sortArr = underScoreSort.split(","); | |
26 | + if(StringUtils.isEmpty(order)){ | |
27 | + sortCondition += columnPreffix+sortArr[0]+" DESC "; | |
28 | + for(int i=1; i<sortArr.length; ++i){ | |
29 | + sortCondition += ","+columnPreffix+sortArr[i]+" DESC "; | |
30 | + } | |
31 | + }else{ | |
32 | + String[] orderArr = order.split(","); | |
33 | + sortCondition += sortArr[0]+" "+orderArr[0]+" "; | |
34 | + for(int i=1; i<sortArr.length; ++i){ | |
35 | + if(i < orderArr.length){ | |
36 | + sortCondition = ","+columnPreffix+sortArr[i]+" "+orderArr[i]+" "; | |
37 | + }else{ | |
38 | + sortCondition = ","+columnPreffix+sortArr[i]+" DESC "; | |
39 | + } | |
40 | + } | |
41 | + } | |
42 | + } | |
43 | + return sortCondition; | |
44 | + } | |
45 | + | |
46 | + /** | |
47 | + * 获取分页 | |
48 | + * @param sort | |
49 | + * @param order | |
50 | + * @param columnPreffix | |
51 | + * @return | |
52 | + */ | |
53 | + public static String getLimitCondition(int page, int pageSize){ | |
54 | + String sql = ""; | |
55 | + if(page < -1){ | |
56 | + page = 0; | |
57 | + if(pageSize < 1){ | |
58 | + pageSize = 0; | |
59 | + } | |
60 | + sql += " limit "+pageSize*(page-1)+","+pageSize; | |
61 | + }else if(page == -1){ | |
62 | + sql = ""; | |
63 | + }else{ | |
64 | + if(pageSize < 1){ | |
65 | + pageSize = 0; | |
66 | + } | |
67 | + sql += " limit "+pageSize*(page-1)+","+pageSize; | |
68 | + } | |
69 | + return sql; | |
70 | + } | |
71 | + | |
72 | + /** | |
73 | + * 创建分页返回 | |
74 | + * @param page | |
75 | + * @param rows | |
76 | + * @param data | |
77 | + * @return | |
78 | + */ | |
79 | + public static Map<String, Object> createPage(int page, int rows, Object data){ | |
80 | + Map<String, Object> pageData = new HashMap<String, Object>(); | |
81 | + pageData.put("page", page); | |
82 | + pageData.put("rows", rows); | |
83 | + pageData.put("data", data); | |
84 | + return pageData; | |
85 | + } | |
86 | +} | ... | ... |
1 | +++ a/src/main/java/com/taover/repository/UtilsString.java | |
... | ... | @@ -0,0 +1,237 @@ |
1 | +package com.taover.repository; | |
2 | + | |
3 | +import java.net.URL; | |
4 | +import java.text.SimpleDateFormat; | |
5 | +import java.util.Date; | |
6 | + | |
7 | +public class UtilsString { | |
8 | + /** | |
9 | + * 格式化日期区间字符串 | |
10 | + * @param source | |
11 | + * @param splitStr | |
12 | + * @param dateFormat | |
13 | + * @return | |
14 | + * @throws Exception | |
15 | + */ | |
16 | + public static Date[] getDateFromString(String source, String splitStr, String dateFormat) throws Exception{ | |
17 | + Date[] resultObj = new Date[2]; | |
18 | + Date createdAtStart = null; | |
19 | + Date createdAtEnd = null; | |
20 | + if(source != null && !"".equals(source)){ | |
21 | + String[] createdAtArr = source.split(splitStr); | |
22 | + SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); | |
23 | + if(createdAtArr.length > 0){ | |
24 | + createdAtStart = sdf.parse(createdAtArr[0]); | |
25 | + } | |
26 | + if(createdAtArr.length > 1){ | |
27 | + createdAtEnd = sdf.parse(createdAtArr[1]); | |
28 | + } | |
29 | + } | |
30 | + resultObj[0] = createdAtStart; | |
31 | + resultObj[1] = createdAtEnd; | |
32 | + return resultObj; | |
33 | + } | |
34 | + | |
35 | + /** | |
36 | + * 获取URL path部分 | |
37 | + * @param url | |
38 | + * @return | |
39 | + */ | |
40 | + public static String getUrlPath(String url){ | |
41 | + if(url == null){ | |
42 | + return null; | |
43 | + } | |
44 | + if(url.startsWith("http")){ | |
45 | + try{ | |
46 | + URL dataUrl = new URL(url); | |
47 | + return dataUrl.getPath(); | |
48 | + }catch(Exception e){ | |
49 | + e.printStackTrace(); | |
50 | + } | |
51 | + } | |
52 | + return url; | |
53 | + } | |
54 | + | |
55 | + /** | |
56 | + * 在compares字符数组查找pattern字符串,找到则返回字串在数组中的索引,未找到返回-1 | |
57 | + * @param pattern | |
58 | + * @param compares | |
59 | + * @return | |
60 | + */ | |
61 | + public static int getStringIndex(String pattern, String compares[]){ | |
62 | + //参数检验 | |
63 | + if(pattern==null || compares==null){ | |
64 | + return -1; | |
65 | + } | |
66 | + | |
67 | + //循环遍历compares | |
68 | + for(int i=0; i<compares.length; ++i){ | |
69 | + if(compares[i].equals(pattern)){ | |
70 | + return i; | |
71 | + } | |
72 | + } | |
73 | + return -1; | |
74 | + } | |
75 | + | |
76 | + /** | |
77 | + * 生成发货单的发货单内部序号, 格式:'D'.date('Ymd') +8位数字 | |
78 | + * @return | |
79 | + */ | |
80 | + public static String getDeliverySn(){ | |
81 | + String result = "D"; | |
82 | + String date = new SimpleDateFormat("yyyyMMdd").format(new Date()); | |
83 | + long temp = System.currentTimeMillis()%100000000; | |
84 | + result = result + date + temp; | |
85 | + return result; | |
86 | + } | |
87 | + | |
88 | + /** | |
89 | + * 通过表名获取BEAN类名 | |
90 | + * @param tableName | |
91 | + * @return | |
92 | + */ | |
93 | + public static String getBeanNameFormTableName(String tableName){ | |
94 | + if (tableName == null) return null; | |
95 | + if (tableName.length() == 0) return ""; | |
96 | + byte[] ss = tableName.toLowerCase().getBytes(); | |
97 | + int len = ss.length; | |
98 | + byte[] ss1 = new byte[len]; | |
99 | + ss1[0] = new String(ss, 0).toUpperCase().getBytes()[0]; | |
100 | + int k = 1; | |
101 | + for (int i = 1; i < ss.length; i++) { | |
102 | + if (ss[i] == '_') { | |
103 | + if (i < ss.length - 1) { | |
104 | + ss1[k] = (byte)Character.toUpperCase(ss[(i + 1)]); | |
105 | + i++; | |
106 | + } | |
107 | + len--; | |
108 | + } else { | |
109 | + ss1[k] = ss[i]; | |
110 | + } | |
111 | + k++; | |
112 | + } | |
113 | + return new String(ss1, 0, len); | |
114 | + } | |
115 | + | |
116 | + /** | |
117 | + * 获取前缀 | |
118 | + * @param value | |
119 | + * @param digitNumber | |
120 | + * @param preffixChar | |
121 | + * @return | |
122 | + */ | |
123 | + public static String getCodeWithPreffix(long value, int digitNumber, char preffixChar){ | |
124 | + String result = ""; | |
125 | + if(value>Long.MAX_VALUE || value<Long.MIN_VALUE){ | |
126 | + return null; | |
127 | + } | |
128 | + for(int i=digitNumber; i>0; --i){ | |
129 | + long baseDiv = (long) Math.pow(10, i-1); | |
130 | + long baseRand = (long) Math.pow(10, i); | |
131 | + long currentDigit = value % baseRand / baseDiv; | |
132 | + if(currentDigit == 0){ | |
133 | + result = result + preffixChar; | |
134 | + }else{ | |
135 | + result = result + currentDigit; | |
136 | + } | |
137 | + } | |
138 | + return result; | |
139 | + } | |
140 | + | |
141 | + /** | |
142 | + * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。</br> | |
143 | + * 例如:HelloWorld->HELLO_WORLD | |
144 | + * @param name 转换前的驼峰式命名的字符串 | |
145 | + * @return 转换后下划线大写方式命名的字符串 | |
146 | + */ | |
147 | + public static String underscoreName(String name) { | |
148 | + StringBuilder result = new StringBuilder(); | |
149 | + if (name != null && name.length() > 0) { | |
150 | + // 将第一个字符处理成大写 | |
151 | + result.append(name.substring(0, 1).toUpperCase()); | |
152 | + // 循环处理其余字符 | |
153 | + for (int i = 1; i < name.length(); i++) { | |
154 | + String s = name.substring(i, i + 1); | |
155 | + // 在大写字母前添加下划线 | |
156 | + if (Character.isUpperCase(s.charAt(0)) && Character.isLetter(s.charAt(0))) { | |
157 | + result.append("_"); | |
158 | + } | |
159 | + // 其他字符直接转成大写 | |
160 | + result.append(s.toUpperCase()); | |
161 | + } | |
162 | + } | |
163 | + return result.toString(); | |
164 | + } | |
165 | + | |
166 | + /** | |
167 | + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br> | |
168 | + * 例如:HELLO_WORLD->HelloWorld | |
169 | + * @param name 转换前的下划线大写方式命名的字符串 | |
170 | + * @return 转换后的驼峰式命名的字符串 | |
171 | + */ | |
172 | + public static String camelName(String name) { | |
173 | + StringBuilder result = new StringBuilder(); | |
174 | + // 快速检查 | |
175 | + if (name == null || name.isEmpty()) { | |
176 | + // 没必要转换 | |
177 | + return ""; | |
178 | + } else if (!name.contains("_")) { | |
179 | + // 不含下划线,仅将首字母小写 | |
180 | + return name.substring(0, 1).toLowerCase() + name.substring(1); | |
181 | + } | |
182 | + // 用下划线将原始字符串分割 | |
183 | + String camels[] = name.split("_"); | |
184 | + for (String camel : camels) { | |
185 | + // 跳过原始字符串中开头、结尾的下换线或双重下划线 | |
186 | + if (camel.isEmpty()) { | |
187 | + continue; | |
188 | + } | |
189 | + // 处理真正的驼峰片段 | |
190 | + if (result.length() == 0) { | |
191 | + // 第一个驼峰片段,全部字母都小写 | |
192 | + result.append(camel.toLowerCase()); | |
193 | + } else { | |
194 | + // 其他的驼峰片段,首字母大写 | |
195 | + result.append(camel.substring(0, 1).toUpperCase()); | |
196 | + result.append(camel.substring(1).toLowerCase()); | |
197 | + } | |
198 | + } | |
199 | + return result.toString(); | |
200 | + } | |
201 | + | |
202 | + public static String getRandomStr(int digitNum){ | |
203 | + int numStartZero = 48; | |
204 | + int charStartUpperA = 65; | |
205 | + int charStartLowerA = 97; | |
206 | + int numSelectCount = 10; | |
207 | + int charSelectCount = 26; | |
208 | + int numCount = numSelectCount+2*charSelectCount; | |
209 | + String randomResult = ""; | |
210 | + for(int i=0; i<digitNum; ++i){ | |
211 | + int currIndex = (int)(Math.random()*numCount); | |
212 | + if(currIndex < numSelectCount){ | |
213 | + currIndex = numStartZero+currIndex; | |
214 | + }else if(currIndex < numSelectCount+charSelectCount){ | |
215 | + currIndex = charStartUpperA+(currIndex-numSelectCount); | |
216 | + }else{ | |
217 | + currIndex = charStartLowerA+(currIndex-numSelectCount-charSelectCount); | |
218 | + } | |
219 | + randomResult += (char)(currIndex)+""; | |
220 | + } | |
221 | + return randomResult; | |
222 | + } | |
223 | + | |
224 | + public static void main(String args[]){ | |
225 | +// System.out.println(getBeanNameFormTableName("asdf_asdf")); | |
226 | +// System.out.println(System.currentTimeMillis()); | |
227 | +// System.out.println(getCodeWithPreffix(1231212, 10, '-')); | |
228 | + /*String dd = "\"{\"success\":true,\"code\":1,\"printedorder_id\":\"1654\",\"error_message\":\"\"}\""; | |
229 | + dd = dd.substring(1, dd.length()-1); | |
230 | + System.out.println(dd); | |
231 | + JSONObject temp = JSONObject.fromObject(dd); | |
232 | + System.out.println(temp.getInt("code"));*/ | |
233 | + | |
234 | + //System.out.println(UtilsString.getUrlPath("https://ss0.umsapi.com/files/de/c1/13/dec11397254b06e1fd8750311ec2bb02ccd8d3dc.jpeg")); | |
235 | + System.out.println(getRandomStr(12)); | |
236 | + } | |
237 | +} | |
0 | 238 | \ No newline at end of file | ... | ... |