这一节就简单贴一下simple-jdbc框架的源码,其实也没多少东西,都很简单的啦。这个小框架就是对之前 文章发布系统博客 中封装的jdbc工具类,进行的一个强化。
目录结构:
1、DBCP_source
package com.simple.core;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
public class DBCP_source {
private static DataSource ds = null;
static {
try {
InputStream e = DBCP_source.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties prop = new Properties();
prop.load(e);
ds = BasicDataSourceFactory.createDataSource(prop);
} catch (Exception arg1) {
throw new ExceptionInInitializerError(arg1);
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (Exception arg5) {
arg5.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
st.close();
} catch (Exception arg4) {
arg4.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception arg3) {
arg3.printStackTrace();
}
}
}
public static void main(String[] args) throws SQLException {
System.out.println(getConnection());
}
}
2、PropertiesUtil
package com.simple.core;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static String getValue(String propertyPath, String key) {
Properties prop = new Properties();
InputStream in = (new PropertiesUtil()).getClass().getResourceAsStream(propertyPath);
try {
prop.load(in);
} catch (IOException arg4) {
arg4.printStackTrace();
}
return (String) prop.get(key);
}
}
3、StringUtils
package com.simple.core;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class StringUtils {
public static String firstCharacterLowerCase(String str) {
String firstCharacter = String.valueOf(str.charAt(0)).toLowerCase();
return firstCharacter + str.substring(1, str.length());
}
public static Object[] extendArray(Object[] array, Object... objects) {
Object[] newArray = null;
if (array.length < 1) {
return objects;
} else {
newArray = new Object[array.length + objects.length];
int i;
for (i = 0; i < array.length; ++i) {
newArray[i] = array[i];
}
for (i = 0; i < objects.length; ++i) {
newArray[array.length + i] = objects[i];
}
return newArray;
}
}
public static String getUUID() {
return UUID.randomUUID().toString();
}
public static Object[] listToObjectArray(List list) {
Object[] objArr = new Object[list.size()];
for (int i = 0; i < objArr.length; ++i) {
objArr[i] = list.get(i);
}
return objArr;
}
public static String nullToEmpty(Object o) {
return o != null ? o.toString() : "";
}
public static String join(List list) {
String str = "";
for (int i = 0; i < list.size(); ++i) {
str = str + (String) list.get(i) + ",";
}
return str.substring(0, str.length() - 1);
}
public static boolean isEmpty(Object o) {
String str = nullToEmpty(o);
return str == null || str.equals("") || str.matches("\\s*");
}
public static boolean isNotEmpty(Object o) {
return !isEmpty(o);
}
public static String defaultValue(String content, String defaultValue) {
return isEmpty(content) ? defaultValue : content;
}
public static String columnToProperty(String column) {
if (isEmpty(column)) {
return "";
} else {
Byte length = Byte.valueOf((byte) column.length());
StringBuilder sb = new StringBuilder(length.byteValue());
boolean i = false;
for (int j = 0; j < length.byteValue(); ++j) {
if (column.charAt(j) != 95) {
sb.append(column.charAt(j));
} else {
while (column.charAt(j + 1) == 95) {
++j;
}
StringBuilder arg10000 = new StringBuilder();
++j;
sb.append(arg10000.append(column.charAt(j)).toString().toUpperCase());
}
}
return sb.toString();
}
}
public static String upperCaseFirstCharacter(String str) {
StringBuilder sb = new StringBuilder();
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; ++i) {
if (i == 0) {
sb.append(String.valueOf(arr[i]).toUpperCase());
} else {
sb.append(String.valueOf(arr[i]));
}
}
return sb.toString();
}
public static String formatDate(Date date, String format) {
String result = "";
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (date != null) {
result = sdf.format(date);
}
return result;
}
public static Date formatString(String str, String format) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(str);
}
public static String getCurrentDateForMysql() {
return formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
}
public static String getCurrentDateForMysql24() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
}
4、SimpleDao
package com.simple.dao;
import com.simple.core.DBCP_source;
import com.simple.core.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class SimpleDao {
private Connection connection = this.getConnection();
public Connection getConnection() {
try {
return this.connection != null ? this.connection : (this.connection = DBCP_source.getConnection());
} catch (SQLException arg1) {
arg1.printStackTrace();
return null;
}
}
public void closeConnection(Connection connection, PreparedStatement statement, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception arg4) {
arg4.fillInStackTrace();
}
}
public JSONObject queryForJsonObject(String sql, Object... objects) {
Map map = this.queryForMap(sql, objects);
return map == null ? null : JSONObject.fromObject(map);
}
public JSONArray queryForJsonArray(String sql, Object... objects) {
return JSONArray.fromObject(this.queryForList(sql, objects));
}
public List> queryForList(String sql, Object... objects) {
ArrayList result = new ArrayList();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = this.connection.prepareStatement(sql);
for (int e = 0; e < objects.length; ++e) {
statement.setObject(e + 1, objects[e]);
}
rs = statement.executeQuery();
while (rs.next()) {
ResultSetMetaData arg10 = rs.getMetaData();
int count = arg10.getColumnCount();
HashMap map = new HashMap();
for (int i = 0; i < count; ++i) {
map.put(arg10.getColumnName(i + 1), rs.getObject(arg10.getColumnName(i + 1)));
}
result.add(map);
}
} catch (SQLException arg9) {
arg9.printStackTrace();
}
return result;
}
public Map queryForMap(String sql, Object... objects) {
new HashMap();
List list = this.queryForList(sql, objects);
if (list.size() != 1) {
return null;
} else {
Map result = (Map) list.get(0);
return result;
}
}
public T queryForBean(String sql, Class clazz, Object... objects) {
Object obj = null;
Map map = null;
Field field = null;
try {
obj = clazz.newInstance();
map = this.queryForMap(sql, objects);
} catch (IllegalAccessException | InstantiationException arg20) {
arg20.printStackTrace();
}
if (map == null) {
return null;
} else {
Iterator arg7 = map.keySet().iterator();
while (arg7.hasNext()) {
String columnName = (String) arg7.next();
Method method = null;
String propertyName = StringUtils.columnToProperty(columnName);
try {
field = clazz.getDeclaredField(propertyName);
} catch (NoSuchFieldException arg18) {
arg18.printStackTrace();
} catch (SecurityException arg19) {
arg19.printStackTrace();
}
String fieldType = field.toString().split(" ")[1];
Object value = map.get(columnName);
if (value != null) {
String setMethodName = "set" + StringUtils.upperCaseFirstCharacter(propertyName);
try {
String e = value.getClass().getName();
if (!fieldType.equalsIgnoreCase(e)) {
if (fieldType.equalsIgnoreCase("java.lang.Integer")) {
value = Integer.valueOf(Integer.parseInt(String.valueOf(value)));
} else if (fieldType.equalsIgnoreCase("java.lang.String")) {
value = String.valueOf(value);
} else if (fieldType.equalsIgnoreCase("java.util.Date")) {
e = "java.util.Date";
String dateStr = String.valueOf(value);
Timestamp ts = Timestamp.valueOf(dateStr);
Date date = new Date(ts.getTime());
value = date;
}
}
method = clazz.getDeclaredMethod(setMethodName, new Class[]{Class.forName(fieldType)});
method.invoke(obj, new Object[]{value});
} catch (Exception arg17) {
arg17.printStackTrace();
}
}
}
return obj;
}
}
public List getColumeList(String table_schema, String table_name) {
String sql_forColumnName = "select COLUMN_NAME from information_schema.columns where table_schema = ? and table_name = ?";
List cloumnList = this.queryForcloumnList(sql_forColumnName, "COLUMN_NAME",
new Object[]{table_schema, table_name});
return cloumnList;
}
public int update(String table_schema, String table_name, Map paramMapper, String keyColumn) {
List cloumnList = this.getColumeList(table_schema, table_name);
ArrayList listValues = new ArrayList();
if (cloumnList.size() < 1) {
try {
throw new Exception("这张表没有一个字段或者表不存在!");
} catch (Exception arg10) {
arg10.printStackTrace();
return 0;
}
} else if (paramMapper == null) {
try {
throw new Exception("需要修改的map不能为空!");
} catch (Exception arg11) {
arg11.printStackTrace();
return 0;
}
} else if (keyColumn != null && paramMapper.get(keyColumn) != null) {
String sql_forUpdate = "update " + table_name + " set ";
byte count = 0;
Iterator arg9 = cloumnList.iterator();
while (arg9.hasNext()) {
String rs = (String) arg9.next();
if (!rs.equals(keyColumn) && StringUtils.isNotEmpty(paramMapper.get(rs))) {
++count;
listValues.add(paramMapper.get(rs));
sql_forUpdate = sql_forUpdate + rs + "=" + "?,";
}
}
if (count == 0) {
try {
throw new Exception("请核实需要保存的字段!");
} catch (Exception arg12) {
arg12.printStackTrace();
return 0;
}
} else {
sql_forUpdate = sql_forUpdate.substring(0, sql_forUpdate.length() - 1);
sql_forUpdate = sql_forUpdate + " where " + keyColumn + "=?";
listValues.add(paramMapper.get(keyColumn));
System.out.println(sql_forUpdate);
int arg14 = this.update(sql_forUpdate, StringUtils.listToObjectArray(listValues));
return arg14;
}
} else {
try {
throw new Exception("请设置修改行的匹配列!");
} catch (Exception arg13) {
arg13.printStackTrace();
return 0;
}
}
}
public int save(String table_schema, String table_name, Map paramMapper) {
List cloumnList = this.getColumeList(table_schema, table_name);
ArrayList listValues = new ArrayList();
if (cloumnList.size() < 1) {
try {
throw new Exception("这张表没有一个字段或者表不存在!");
} catch (Exception arg9) {
arg9.printStackTrace();
return 0;
}
} else if (paramMapper == null) {
try {
throw new Exception("需要保存的map不能为空!");
} catch (Exception arg10) {
arg10.printStackTrace();
return 0;
}
} else {
String sql_forInsert = "insert into " + table_name + "(";
sql_forInsert = sql_forInsert + StringUtils.join(cloumnList) + ") values (";
byte count = 0;
Iterator arg8 = cloumnList.iterator();
while (arg8.hasNext()) {
String rs = (String) arg8.next();
if (StringUtils.isNotEmpty(paramMapper.get(rs))) {
++count;
listValues.add(paramMapper.get(rs));
sql_forInsert = sql_forInsert + "?,";
} else {
sql_forInsert = sql_forInsert + "NULL,";
}
}
if (count == 0) {
try {
throw new Exception("请核实需要保存的字段!");
} catch (Exception arg11) {
arg11.printStackTrace();
return 0;
}
} else {
sql_forInsert = sql_forInsert.substring(0, sql_forInsert.length() - 1) + ")";
int arg12 = this.update(sql_forInsert, StringUtils.listToObjectArray(listValues));
return arg12;
}
}
}
public List queryForcloumnList(String sql, String columnName, Object... objects) {
JSONArray jsonArray = this.queryForJsonArray(sql, objects);
ArrayList resultList = new ArrayList();
for (int i = 0; i < jsonArray.size(); ++i) {
JSONObject json = (JSONObject) jsonArray.get(i);
resultList.add(json.getString(columnName));
}
return resultList;
}
public String queryForString(String sql, Object... objects) {
JSONObject jsonObject = this.queryForJsonObject(sql, objects);
Iterator sIterator = jsonObject.keys();
if (sIterator.hasNext()) {
String key = (String) sIterator.next();
String value = jsonObject.getString(key);
return value;
} else {
return null;
}
}
public int queryForInt(String sql, Object... objects) {
return Integer.parseInt(this.queryForString(sql, objects));
}
public long queryForLong(String sql, Object... objects) {
return Long.parseLong(this.queryForString(sql, objects));
}
public int update(String sql, Object... objects) {
PreparedStatement statement = null;
try {
statement = this.connection.prepareStatement(sql);
for (int e = 0; e < objects.length; ++e) {
statement.setObject(e + 1, objects[e]);
}
return statement.executeUpdate();
} catch (SQLException arg4) {
arg4.printStackTrace();
return 0;
}
}
public long getTotal(String sql, Object... objects) {
sql = "select count(1) from (" + sql + ") t";
long total = this.queryForLong(sql, objects);
return total;
}
public Map queryForPage(String sql, int pageIndex, int pageSize, Object... objects) {
HashMap pageMap = new HashMap();
int startIndex = (pageIndex - 1) * pageSize;
long total = this.getTotal(sql, objects);
pageMap.put("total", Long.valueOf(total));
sql = sql + " limit ?,?";
JSONArray rows = this.queryForJsonArray(sql,
StringUtils.extendArray(objects, new Object[]{Integer.valueOf(startIndex), Integer.valueOf(pageSize)}));
pageMap.put("rows", rows);
System.out.println(rows.size());
return pageMap;
}
}
真正的源码我貌似不小心删掉了,这个是jar包反编译出来的,所以有些变量名比较奇怪。好吧,小细节不用在意。。。