JDBC——数据库连接池以及JDBC代码模版模版

该代码模版由三部分组成,一个是数据库连接池,一个是数据库常用操作的模版抽象,还有一个是重写的连接对象,主要重写关闭连接的方法,将其改为释放到连接池。

OolongConnectionPool.java

package com.oolong.fs.util.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List; public class OolongConnectionPool { private String driverName;
private String url;
private String userName;
private String password; private int minConnections = 1; // 空闲池,最小连接数
private int maxConnections = 10; // 空闲池,最大连接数
private int initConnections = 5; // 初始化连接数 private List<Connection> freeConnections;
private List<Connection> activeConnections; private static OolongConnectionPool pool;
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>(); public static OolongConnectionPool getInstance() throws Exception {
if (pool != null) {
return pool;
} throw new Exception("数据池未初始化");
} public static void init(String driverName, String url, String userName, String password) {
if (pool == null) {
pool = new OolongConnectionPool(driverName, url, userName, password);
}
} private OolongConnectionPool(String driverName, String url, String userName, String password) {
this.driverName = driverName;
this.url = url;
this.userName = userName;
this.password = password; freeConnections = new LinkedList<>();
activeConnections = new LinkedList<>(); try {
Class.forName(driverName);
Connection conn = null; for (int i = 0; i < initConnections; i++) {
conn = newConnection();
freeConnections.add(conn);
} } catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} private Connection newConnection() throws SQLException {
Connection conn = DriverManager.getConnection(url, userName, password);
OolongConnection oolongConn = new OolongConnection(conn, this);
return oolongConn;
} public synchronized Connection getConnection() {
Connection conn = null; try {
if (freeConnections.size() > 0) {
conn = freeConnections.get(0);
freeConnections.remove(0);
} if (!isValid(conn)) {
conn = newConnection();
}
threadLocal.set(conn); // 将该连接与当前线程关联
activeConnections.add(conn); } catch (SQLException e) {
e.printStackTrace();
} return conn;
} public synchronized void releaseConnection(Connection conn) {
activeConnections.remove(conn);
threadLocal.remove();
if (isValid(conn) && freeConnections.size() < maxConnections) {
freeConnections.add(conn);
} else {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} public Connection getCurrentConnection() {
// 默认线程里面取
Connection conn = threadLocal.get();
if (!isValid(conn)) {
conn = getConnection();
}
return conn;
} private boolean isValid(Connection conn) {
try {
if (conn == null || conn.isClosed()) {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
}

DbHelper.java

package com.oolong.fs.util.db;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.oolong.fs.util.Constant; public class DbHelper { public static List<Map<String, Object>> executeQuery(String sql) {
return executeQuery(sql, new String[0]);
} public static List<Map<String, Object>> executeQuery(String sql, String[] param) {
System.out.println(sql);
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<Map<String, Object>> resut = new ArrayList<>();
Map<String, Object> map = null;
try{
conn = OolongConnectionPool.getInstance().getCurrentConnection();
pst = conn.prepareStatement(sql); for (int i = 0; i < param.length; i++) {
pst.setString(i+1, param[i]);
} rs = pst.executeQuery(); ResultSetMetaData rsm = rs.getMetaData();
String[] columns = new String[rsm.getColumnCount()]; for (int i = 0; i < rsm.getColumnCount(); i++) {
columns[i] = rsm.getColumnName(i + 1);
} rs.beforeFirst(); while(rs.next()) {
map = new HashMap<>();
for(String col : columns) {
map.put(col, rs.getObject(col));
}
resut.add(map);
}
rs.close();
pst.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return resut;
} public static int executeUpdate(String sql, String[] param) {
System.out.println(sql);
Connection conn = null;
PreparedStatement pst = null;
int res = 0; try{
conn = OolongConnectionPool.getInstance().getCurrentConnection();
pst = conn.prepareStatement(sql); for (int i = 0; i < param.length; i++) { if (Constant.DB_NULL.equals(param[i])) {
pst.setNull(i+1, Types.VARCHAR);
} else {
pst.setString(i+1, param[i]);
}
} res = pst.executeUpdate(); pst.close(); // 如果手动管理事务,则连接的关闭在事物管理处手动处理
if (!conn.getAutoCommit()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return res;
} public static int batchInsert(String sql, List<String[]> params) {
System.out.println(sql);
Connection conn = null;
PreparedStatement pst = null;
int res = 0; try{
conn = OolongConnectionPool.getInstance().getCurrentConnection();
pst = conn.prepareStatement(sql); for (String[] param : params) {
for (int i = 0; i < param.length; i++) { if (Constant.DB_NULL.equals(param[i])) {
pst.setNull(i+1, Types.VARCHAR);
} else {
pst.setString(i+1, param[i]);
}
}
pst.addBatch();
} pst.executeBatch(); pst.close(); // 如果手动管理事务,则连接的关闭在事物管理处手动处理
if (!conn.getAutoCommit()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return res;
} public static <T> List<T> fillModel(List<Map<String, Object>> data, Class<T> cls
, List<String> columns) { List<T> res = new ArrayList<>();
T bean = null; try {
for (Map<String, Object> row : data) {
bean = cls.newInstance(); for(String field : columns) {
Method method = getMethod(field, cls);
method.invoke(bean, row.get(field));
}
res.add(bean);
} } catch(Exception e) {
e.printStackTrace();
} return res;
} private static <T> Method getMethod(String field, Class<T> cls) { if (field.startsWith("is")) {
return getBooleanSetter(field, cls);
} else {
return getStringSetter(field, cls);
}
} /**
* 到当前类中找setter方法,如果找不到,就到父类中找(针对一般类型)
* @param field
* @param cls
* @return
*/
private static <T> Method getStringSetter(String field, Class<T> cls) {
Method method = null; try {
Field property = cls.getDeclaredField(field);
method = cls.getDeclaredMethod("set"
+ field.substring(0, 1).toUpperCase()
+ field.substring(1), property.getType()); } catch (NoSuchFieldException e) {
Class sup = cls.getSuperclass();
return getStringSetter(field, sup);
} catch (Exception e) {
e.printStackTrace();
} return method;
} /**
* 到当前类中找setter方法,如果找不到,就到父类中找(针对布尔类型)
* @param field
* @param cls
* @return
*/
private static <T> Method getBooleanSetter(String field, Class<T> cls) {
Method method = null; try {
Field property = cls.getDeclaredField(field);
method = cls.getDeclaredMethod("set"
+ field.substring(2, field.length()), property.getType()); } catch (NoSuchFieldException e) {
Class sup = cls.getSuperclass();
return getBooleanSetter(field, sup); } catch (Exception e) {
e.printStackTrace();
} return method;
}
}

OolongConnection.java

package com.oolong.fs.util.db;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor; public class OolongConnection implements Connection { private Connection conn;
private OolongConnectionPool pool; public OolongConnection(Connection conn, OolongConnectionPool pool) {
this.conn = conn;
this.pool = pool;
} @Override
public void close() throws SQLException {
pool.releaseConnection(conn); // 修改 close() 方法
} @Override
public boolean isClosed() throws SQLException {
return conn.isClosed();
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return conn.unwrap(iface);
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return conn.isWrapperFor(iface);
} @Override
public Statement createStatement() throws SQLException {
return conn.createStatement();
} @Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
} @Override
public CallableStatement prepareCall(String sql) throws SQLException {
return conn.prepareCall(sql);
} @Override
public String nativeSQL(String sql) throws SQLException {
return conn.nativeSQL(sql);
} @Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
conn.setAutoCommit(autoCommit);
} @Override
public boolean getAutoCommit() throws SQLException {
return conn.getAutoCommit();
} @Override
public void commit() throws SQLException {
conn.commit();
} @Override
public void rollback() throws SQLException {
conn.rollback();
} @Override
public DatabaseMetaData getMetaData() throws SQLException {
return conn.getMetaData();
} @Override
public void setReadOnly(boolean readOnly) throws SQLException {
conn.setReadOnly(readOnly);
} @Override
public boolean isReadOnly() throws SQLException {
return conn.isReadOnly();
} @Override
public void setCatalog(String catalog) throws SQLException {
conn.setCatalog(catalog);
} @Override
public String getCatalog() throws SQLException {
return conn.getCatalog();
} @Override
public void setTransactionIsolation(int level) throws SQLException {
conn.setTransactionIsolation(level);
} @Override
public int getTransactionIsolation() throws SQLException {
return conn.getTransactionIsolation();
} @Override
public SQLWarning getWarnings() throws SQLException {
return conn.getWarnings();
} @Override
public void clearWarnings() throws SQLException {
conn.clearWarnings();
} @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return conn.createStatement(resultSetType, resultSetConcurrency);
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return conn.prepareCall(sql, resultSetType, resultSetConcurrency);
} @Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return conn.getTypeMap();
} @Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
conn.setTypeMap(map);
} @Override
public void setHoldability(int holdability) throws SQLException {
conn.setHoldability(holdability);
} @Override
public int getHoldability() throws SQLException {
return conn.getHoldability();
} @Override
public Savepoint setSavepoint() throws SQLException {
return conn.setSavepoint();
} @Override
public Savepoint setSavepoint(String name) throws SQLException {
return conn.setSavepoint(name);
} @Override
public void rollback(Savepoint savepoint) throws SQLException {
conn.rollback(savepoint);
} @Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
conn.releaseSavepoint(savepoint);
} @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return conn.prepareStatement(sql, autoGeneratedKeys);
} @Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return conn.prepareStatement(sql, columnIndexes);
} @Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return conn.prepareStatement(sql, columnNames);
} @Override
public Clob createClob() throws SQLException {
return conn.createClob();
} @Override
public Blob createBlob() throws SQLException {
return conn.createBlob();
} @Override
public NClob createNClob() throws SQLException {
return conn.createNClob();
} @Override
public SQLXML createSQLXML() throws SQLException {
return conn.createSQLXML();
} @Override
public boolean isValid(int timeout) throws SQLException {
return conn.isValid(timeout);
} @Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
conn.setClientInfo(name, value);
} @Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
conn.setClientInfo(properties);
} @Override
public String getClientInfo(String name) throws SQLException {
return conn.getClientInfo(name);
} @Override
public Properties getClientInfo() throws SQLException {
return conn.getClientInfo();
} @Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return conn.createArrayOf(typeName, elements);
} @Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return conn.createStruct(typeName, attributes);
} @Override
public void setSchema(String schema) throws SQLException {
conn.setSchema(schema);
} @Override
public String getSchema() throws SQLException {
return conn.getSchema();
} @Override
public void abort(Executor executor) throws SQLException {
conn.abort(executor);
} @Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
conn.setNetworkTimeout(executor, milliseconds);
} @Override
public int getNetworkTimeout() throws SQLException {
return conn.getNetworkTimeout();
} }

使用之前需要先初始化连接池:

OolongConnectionPool.init("com.mysql.jdbc.Driver"
, "jdbc:mysql://localhost:3306/fileshare?useSSL=true"
, "root", "123");

下面是一些具体调用的示例:

package com.oolong.fs.file.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map; import com.oolong.fs.file.dao.ProjectDao;
import com.oolong.fs.file.dao.condition.ProjectCondition;
import com.oolong.fs.file.model.ProjectModel;
import com.oolong.fs.util.Constant;
import com.oolong.fs.util.StringUtil;
import com.oolong.fs.util.db.DbHelper; public class ProjectDaoImpl implements ProjectDao { private static String columnStr;
private static List<String> columns;
private static String table = "t_file_project"; static {
columns = new ArrayList<>();
columns.add("wid");
columns.add("name");
columns.add("description");
columns.add("createUser");
columns.add("createTime");
columns.add("parentWid");
columns.add("scope");
columns.add("status"); columnStr = String.join(",", columns);
} @Override
public List<ProjectModel> findByCondition(ProjectCondition condition) {
List<String> params = new ArrayList<>(); StringBuilder sql = new StringBuilder();
sql.append(Constant.SQL_SELECT).append(columnStr).append(" FROM ")
.append(table).append(Constant.SQL_WHERE); buildScopeCondition(sql, params, condition);
buildParentCondition(sql, params, condition);
buildStatusCondition(sql, params, condition);
buildCreateUserCondition(sql, params, condition);
buildKeyworkCondition(sql, params, condition); sql.append("1 = 1"); String[] par = new String[params.size()]; for (int i = 0; i < params.size(); i++) {
par[i] = params.get(i);
} List<Map<String, Object>> res = DbHelper.executeQuery(sql.toString(), par);
List<ProjectModel> models = DbHelper.fillModel(res, ProjectModel.class, columns);
return models;
} private void buildScopeCondition(StringBuilder sql, List<String> params, ProjectCondition condition) {
if (!condition.isAdmin() && !(condition.getScope() < 0)) {
sql.append("scope = ?").append(Constant.SQL_AND);
params.add(condition.getScope() + "");
}
} private void buildParentCondition(StringBuilder sql, List<String> params, ProjectCondition condition) {
if (!StringUtil.isEmpty(condition.getParentWid())) {
sql.append("parentWid = ?").append(Constant.SQL_AND);
params.add(condition.getParentWid());
}
} private void buildStatusCondition(StringBuilder sql, List<String> params, ProjectCondition condition) {
if (!(condition.getStatus() < 0)) {
sql.append("status = ?").append(Constant.SQL_AND);
params.add(condition.getStatus() + "");
}
} private void buildCreateUserCondition(StringBuilder sql, List<String> params, ProjectCondition condition) {
if (!StringUtil.isEmpty(condition.getCreateUser())) {
sql.append("createUser = ?").append(Constant.SQL_AND);
params.add(condition.getCreateUser());
}
} private void buildKeyworkCondition(StringBuilder sql, List<String> params, ProjectCondition condition) {
if (!StringUtil.isEmpty(condition.getKeyword())) {
sql.append("("); sql.append("name like ?").append(Constant.SQL_OR);
params.add("%" + condition.getKeyword() + "%"); sql.append("description like ?");
params.add("%" + condition.getKeyword() + "%"); sql.append(")").append(Constant.SQL_AND);
}
} @Override
public List<ProjectModel> findByWids(boolean isIn, List<String> wids) { StringBuilder sql = new StringBuilder();
sql.append(Constant.SQL_SELECT).append(columnStr).append(" FROM ")
.append(table).append(Constant.SQL_WHERE); if (isIn) {
sql.append("wid in ('");
} else {
sql.append("wid not in ('");
} sql.append(String.join("','", wids)).append("')"); System.out.println(sql.toString()); List<Map<String, Object>> res = DbHelper.executeQuery(sql.toString());
List<ProjectModel> models = DbHelper.fillModel(res, ProjectModel.class, columns);
return models;
} @Override
public List<ProjectModel> fingParticipantProjectsByUserWid(String userWid) {
String sql = Constant.SQL_SELECT + columnStr + " FROM " + table + " where wid = "
+ "(SELECT projectWid FROM fileshare.t_file_member where userWid= ? )";
List<Map<String, Object>> res = DbHelper.executeQuery(sql, new String[]{userWid});
List<ProjectModel> models = DbHelper.fillModel(res, ProjectModel.class, columns);
return models;
} @Override
public ProjectModel findByWid(String wid) {
String sql = Constant.SQL_SELECT + columnStr + " FROM " + table + " where wid = ?";
List<Map<String, Object>> res = DbHelper.executeQuery(sql, new String[]{wid});
List<ProjectModel> models = DbHelper.fillModel(res, ProjectModel.class, columns);
return models.size() > 0 ? models.get(0) : null;
} @Override
public int insert(ProjectModel model) {
String sql = Constant.SQL_INSERT + table + " (" + columnStr.replace("createTime,", "")
+ ") VALUES (?, ?, ?, ?, ?, ?, ?)";
String[] param = new String[]{
model.getWid(), model.getName(), model.getDescription(),
model.getCreateUser(), model.getParentWid(), model.getScope() + "",
model.getStatus() + ""
};
return DbHelper.executeUpdate(sql, param);
} @Override
public int update(ProjectModel model) {
StringBuilder sql = new StringBuilder();
List<String> params = new ArrayList<>();
sql.append(Constant.SQL_UPDATE).append(table).append(" SET "); if (!StringUtil.isEmpty(model.getName())) {
sql.append("name = ?").append(Constant.SQL_COMMA);
params.add(model.getName());
} if (!StringUtil.isEmpty(model.getDescription())) {
sql.append("description = ?").append(Constant.SQL_COMMA);;
params.add(model.getDescription());
} if (model.getScope() >= 0) {
sql.append("scope = ?").append(Constant.SQL_COMMA);
params.add(model.getScope() + "");
} if (model.getStatus() >= 0 ) {
sql.append("status = ?").append(Constant.SQL_COMMA);
params.add(model.getStatus() + "");
} if (!StringUtil.isEmpty(model.getParentWid())) {
sql.append("parentWid = ?");
params.add(model.getParentWid());
} sql.append(Constant.SQL_WHERE).append("wid = ?");
params.add(model.getWid()); String[] par = new String[params.size()];
for (int i = 0; i < params.size(); i++) {
par[i] = params.get(i);
} return DbHelper.executeUpdate(sql.toString(), par);
} @Override
public int delete(String wid) {
//逻辑删除
String sql = Constant.SQL_UPDATE + table + " SET status =1 "+" where wid = ?";
String[] params = new String[]{wid}; return DbHelper.executeUpdate(sql, params);
} @Override
public List<String> FindRoleWidsByUserWid(String userWid) {
String sql = Constant.SQL_SELECT + "roleWid FROM t_auth_rel_role_usergroup where usergroupWid in ("
+Constant.SQL_SELECT + "groupWid FROM t_auth_rel_user_group where userWid = ? )";
List<Map<String, Object>> res = DbHelper.executeQuery(sql, new String[]{userWid});
List<String> result = new ArrayList<>();
for (Map<String, Object> re : res) {
for (Map.Entry<String, Object> r : re.entrySet()) {
result = (List<String>) r.getValue();
}
} return result;
} @Override
public List<ProjectModel> findAll() {
String sql = Constant.SQL_SELECT + columnStr + " FROM " + table ;
List<Map<String, Object>> res = DbHelper.executeQuery(sql);
List<ProjectModel> projects = DbHelper.fillModel(res, ProjectModel.class, columns);
return projects;
} }
上一篇:CentOS 7下给nginx安装SSL证书


下一篇:JDBC编程学习笔记之数据库连接池的实现