Configurations.java
package com.dbutils.common;
import java.sql.*;
import java.util.*;
import java.lang.reflect.*;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 数据库管理
*
* */
@SuppressWarnings("unchecked")
public class Configurations {
private final static Log logger = LogFactory.getLog(Configurations.class);
private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();
private static DataSource dataSource;
private static boolean show_sql = true;
private static BasicDataSource dbcpDataSource = null;
private static ResourceBundle res = null;
static {
initDataSource(null);
}
/**
* 初始化连接池
*
* @param props
* @param show_sql
*/
private final static void initDataSource(Properties dbProperties) {
try {
// 配置dbcp数据源
if (dbcpDataSource == null) {
dbcpDataSource = new BasicDataSource();
res = ResourceBundle.getBundle("oracleConfig");
}
String driverClassName = res.getString("driverClassName");
int initialSize = Integer.valueOf(res.getString("initialSize"));
int maxActive = Integer.valueOf(res.getString("maxActive"));
int maxIdle = Integer.valueOf(res.getString("maxIdle"));
int minIdle = Integer.valueOf(res.getString("minIdle"));
int maxWait = Integer.valueOf(res.getString("maxWait"));
Boolean logAbandoned = Boolean.valueOf(res
.getString("logAbandoned"));
Boolean removeAbandoned = Boolean.valueOf(res
.getString("removeAbandoned"));
int removeAbandonedTimeout = Integer.valueOf(res
.getString("removeAbandonedTimeout"));
Boolean testWhileIdle = Boolean.valueOf(res
.getString("testWhileIdle"));
Boolean testOnBorrow = Boolean.valueOf(res
.getString("testOnBorrow"));
Boolean testOnReturn = Boolean.valueOf(res
.getString("testOnReturn"));
int timeBetweenEvictionRunsMillis = Integer.valueOf(res
.getString("timeBetweenEvictionRunsMillis"));
int numTestsPerEvictionRun = Integer.valueOf(res
.getString("numTestsPerEvictionRun"));
int minEvictableIdleTimeMillis = Integer.valueOf(res
.getString("minEvictableIdleTimeMillis"));
String validationQuery = res.getString("validationQuery");
String url = res.getString("oracleurl");
String userName = res.getString("oracleuser");
String password = res.getString("oraclepassword");
if ("show_sql".equalsIgnoreCase("true")) {
// show_sql =
// "true".equalsIgnoreCase(dbProperties.getProperty(skey));
// dbcpDataSource.
}
dbcpDataSource.setUrl(url);
dbcpDataSource.setDriverClassName(driverClassName);
dbcpDataSource.setUsername(userName);
dbcpDataSource.setPassword(password);
dbcpDataSource.setDefaultAutoCommit(true);
dbcpDataSource.setInitialSize(initialSize);
dbcpDataSource.setMaxActive(maxActive);
dbcpDataSource.setMinIdle(minIdle);
dbcpDataSource.setMaxIdle(maxIdle);
dbcpDataSource.setMaxWait(maxWait);
dbcpDataSource.setLogAbandoned(logAbandoned);
dbcpDataSource.setRemoveAbandoned(removeAbandoned);
dbcpDataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
dbcpDataSource.setTestOnBorrow(testOnBorrow);
dbcpDataSource.setTestOnReturn(testOnReturn);
dbcpDataSource.setTestWhileIdle(testWhileIdle);
dbcpDataSource
.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dbcpDataSource.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
dbcpDataSource
.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dbcpDataSource.setValidationQuery(validationQuery);
Configurations.dataSource = (DataSource) dbcpDataSource;
Connection conn = getConnection();
DatabaseMetaData mdm = conn.getMetaData();
logger.info("Connected to " + mdm.getDatabaseProductName() + " "
+ mdm.getDatabaseProductVersion());
closeConnection();
logger.info("Initialize DbHelper");
} catch (Exception e) {
throw new DBException(e);
}
}
/**
* 断开连接池
*/
public final static void closeDataSource() {
try {
dataSource.getClass().getMethod("close").invoke(dataSource);
} catch (NoSuchMethodException e) {
} catch (Exception e) {
logger.error("Unabled to destroy DataSource!!! ", e);
}
}
public final static Connection getConnection() throws SQLException {
Connection conn = conns.get();
if (conn == null || conn.isClosed()) {
conn = dataSource.getConnection();
conns.set(conn);
}
return conn;
}
/**
* 关闭连接
*/
public final static void closeConnection() {
Connection conn = conns.get();
try {
if (conn != null && !conn.isClosed()) {
conn.setAutoCommit(true);
conn.close();
}
} catch (SQLException e) {
logger.error("Unabled to close connection!!! ", e);
}
conns.set(null);
}
/**
* 用于跟踪执行的SQL语句
*
* @author Winter Lau
*/
static class _DebugConnection implements InvocationHandler {
private final static Log logger = LogFactory
.getLog(_DebugConnection.class);
private Connection conn = null;
public _DebugConnection(Connection conn) {
this.conn = conn;
}
/**
* Returns the conn.
*
* @return Connection
*/
public Connection getConnection() {
return (Connection) Proxy.newProxyInstance(conn.getClass()
.getClassLoader(), conn.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
try {
String method = m.getName();
if ("prepareStatement".equals(method)
|| "createStatement".equals(method))
logger.info("[SQL] >>> " + args[0]);
return m.invoke(conn, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
}
BaseDao.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dbutils.common;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
/**
* 基于DBUtils
* BaseDAO 数据库连接基础类
*/
@SuppressWarnings("hiding")
public interface BaseDao<T, PK extends Serializable> {
/**
* 获取数据库连接
*
* @return
*/
public Connection getConnection();
/**
* 关闭连接
*
* @return
*
* @return
*/
public void CloseConnection();
/**
* 执行查询,将某一行的结果保存到Bean中,
*
* @param entityClass
* 类名
* @param sql
* sql语句
* @return 查询结果
*/
public <T> T findBean(Class<T> beanClass, String sql,
Object... params);
// 功能同上 没有传入参数 老接口方法 保留
public <T> T findBean(Class<T> beanClass, String sql);
/**
* 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中
*
* @param entityClass
* 类名
* @param sql
* sql语句
* @return 查询结果
*/
public <T> List<T> findList(Class<T> beanClass, String sql,
Object... params) ;
// 功能同上 没有传入参数 老接口方法 保留
public <T> List<T> findList(Class<T> beanClass, String sql);
/**
* 查询记录总条数
*
* @param sql
* sql语句
* @return 记录总数
*/
public long getCount(String sql, Object... params) ;
// 功能同上 没有传入参数 老接口方法 保留
public int count(String sql);
/**
* 执行INSERT/UPDATE/DELETE语句
*
* @param sql
* @param params
* @return
*/
public int update(String sql, Object... params);
/**
* 批量执行指定的SQL语句
*
* @param sql
* @param params
* @return
* @throws DBException
*/
public int[] batch(String sql, Object[][] params);
public int deleteByid(Class<T> beanClass, String id) ;
public int deleteByid(Class<T> beanClass, int id);
/**
* 执行查询,将某一行的结果保存到Bean中,
*
* @param entityClass
* 类名
* @param id 主键或者唯一标示ID
*
* @return 查询结果
*/
public <T> T findById(Class<T> beanClass, int id);
public boolean save(Object obj) throws Exception ;
public boolean update(Object obj) throws Exception ;
public boolean delete(Object obj, Integer id) throws Exception ;
}
BaseDaoImpl.java
package com.dbutils.common;
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
/**
* 基于DBUtils BaseDAO 数据库连接基础类
*/
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {
private final static QueryRunner _g_runner = new QueryRunner();
private final static ColumnListHandler _g_columnListHandler = new ColumnListHandler() {
@Override
protected Object handleRow(ResultSet rs) throws SQLException {
Object obj = super.handleRow(rs);
if (obj instanceof BigInteger)
return ((BigInteger) obj).longValue();
return obj;
}
};
private final static ScalarHandler _g_scaleHandler = new ScalarHandler() {
@Override
public Object handle(ResultSet rs) throws SQLException {
Object obj = super.handle(rs);
if (obj instanceof BigInteger)
return ((BigInteger) obj).longValue();
return obj;
}
};
private final static List<Class<?>> PrimitiveClasses = new ArrayList<Class<?>>() {
{
add(Long.class);
add(Integer.class);
add(String.class);
add(java.util.Date.class);
add(java.sql.Date.class);
add(java.sql.Timestamp.class);
}
};
private final static boolean _IsPrimitive(Class<?> cls) {
return cls.isPrimitive() || PrimitiveClasses.contains(cls);
}
/**
* 获取数据库连接
*
* @return
*/
public Connection getConnection() {
try {
return Configurations.getConnection();
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 关闭连接
*
* @return
*
* @return
*/
public void CloseConnection() {
Configurations.closeConnection();
}
/**
* 执行查询,将某一行的结果保存到Bean中,
*
* @param entityClass
* 类名
* @param sql
* sql语句
* @return 查询结果
*/
public <T> T findBean(Class<T> beanClass, String sql,
Object... params) {
try {
return (T) _g_runner.query(getConnection(), sql,
_IsPrimitive(beanClass) ? _g_scaleHandler
: new BeanHandler(beanClass), params);
} catch (SQLException e) {
throw new DBException(e);
}
}
// 功能同上 没有传入参数 老接口方法 保留
public <T> T findBean(Class<T> beanClass, String sql) {
try {
return (T) _g_runner.query(getConnection(), sql,
_IsPrimitive(beanClass) ? _g_scaleHandler
: new BeanHandler(beanClass));
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 执行查询,将每行的结果保存到Bean中,然后将所有Bean保存到List中
*
* @param entityClass
* 类名
* @param sql
* sql语句
* @return 查询结果
*/
public <T> List<T> findList(Class<T> beanClass, String sql,
Object... params) {
try {
return (List<T>) _g_runner.query(getConnection(), sql,
_IsPrimitive(beanClass) ? _g_columnListHandler
: new BeanListHandler(beanClass), params);
} catch (SQLException e) {
throw new DBException(e);
}
}
// 功能同上 没有传入参数 老接口方法 保留
public <T> List<T> findList(Class<T> beanClass, String sql) {
try {
return (List<T>) _g_runner.query(getConnection(), sql,
_IsPrimitive(beanClass) ? _g_columnListHandler
: new BeanListHandler(beanClass));
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 执行统计查询语句,语句的执行结果必须只返回一个数值
*
* @param sql
* @param params
* @return
*/
public long stat(String sql, Object... params) {
try {
Number num = (Number) _g_runner.query(getConnection(), sql,
_g_scaleHandler, params);
return (num != null) ? num.longValue() : -1;
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 查询记录总条数
*
* @param sql
* sql语句
* @return 记录总数
*/
public long getCount(String sql, Object... params) {
Number value = null;
if (value == null) {
value = stat(sql, params);
}
return value.longValue();
}
// 功能同上 没有传入参数 老接口方法 保留
public int count(String sql) {
Number num = 0;
int count = 0;
count = (int) stat(sql);
count = (num != null) ? num.intValue() : 0;
return count;
}
/**
* 执行INSERT/UPDATE/DELETE语句
*
* @param sql
* @param params
* @return
*/
public int update(String sql, Object... params) {
try {
return _g_runner.update(getConnection(), sql, params);
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 批量执行指定的SQL语句
* @param sql
* @param params
* @return
* @throws DBException
*/
public int[] batch(String sql, Object[][] params) {
try {
return _g_runner.batch(getConnection(), sql, params);
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* 按ID号删除某条记录
* @param entityClass
* 类名
* @return 0(删除失败),1(删除成功)
* @throws DBException
*/
public int deleteByid(Class<T> beanClass, int id) {
try {
String sql="delete from "+ beanClass.getSimpleName() + " where id = ?";
_g_runner.update(getConnection(),sql,id);
return 1;
} catch (SQLException e) {
return 0;
}
}
/**
* 按ID号删除多条记录
* @param entityClass
* 类名
* @return 0(删除失败),1(删除成功)
* @throws DBException
*/
public int deleteByid(Class<T> beanClass, String id) {
try {
String sql="delete from "+ beanClass.getSimpleName() + " where id in ("+id+")";
_g_runner.update(getConnection(),sql);
return 1;
} catch (SQLException e) {
return 0;
}
}
/**
* 执行查询,将某一行的结果保存到Bean中,
* @param entityClass
* 类名
* @param id 主键或者唯一标示ID
* @return 查询结果
*/
public <T> T findById(Class<T> beanClass, int id) {
try {
String sql = "select * from " + beanClass.getSimpleName()
+ " where id = ?";
return (T) _g_runner.query(getConnection(), sql,
_IsPrimitive(beanClass) ? _g_scaleHandler
: new BeanHandler(beanClass), id);
} catch (SQLException e) {
throw new DBException(e);
}
}
public boolean save(Object obj) throws Exception {
SqlTemplate sqlTemp =new SqlTemplate();
// 获取obj的属性的值
List list = sqlTemp.getFields(obj);
// 获取sql
String sql =sqlTemp.getInsertSQL(obj);
System.out.println(sql);
// 通过DbUtil//连接数据库
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i <= list.size(); i++) {
ps.setObject(i, list.get(i - 1));
}
boolean flag = ps.executeUpdate() > 0 ? true : false;
CloseConnection();
return flag;
}
public boolean update(Object obj) throws Exception {
SqlTemplate sqlTemp =new SqlTemplate();
// 获取obj的属性的值
List list = sqlTemp.getFields(obj);
// 获取sql
String sql =sqlTemp.getUpdateSQL(obj);
// 通过DbUtil
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i < list.size(); i++) {
ps.setObject(i, list.get(i));
}
ps.setInt(list.size(), (Integer) list.get(0));
boolean flag = ps.executeUpdate() > 0 ? true : false;
CloseConnection();
return flag;
}
public boolean delete(Object obj, Integer id) throws Exception {
SqlTemplate sqlTemp =new SqlTemplate();
// 获取obj的属性的值
List list = sqlTemp.getFields(obj);
// 获取sql
String sql =sqlTemp.getDeleteSQL(obj);
// 通过DbUtil
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
boolean flag = ps.executeUpdate() > 0 ? true : false;
CloseConnection();
return flag;
}
}
SqlTemplate.java
package com.dbutils.common;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* 规定: 1.数据表名 “tb_” + “对象名” 2.数据库字段顺序与对应实体属性顺序一致(不是必须的,但是ID必须是第一个属性)
* 功能:通过反射实现CRUD 使用:继承该类,调用对应方法,传入对象类型 DbUtil.为自定义操作数据库工具类
*
* @author Administrator
*
*/
public class SqlTemplate {
public final static String TABLE_PREFIX = "";
private String tableName = "";
private Field[] fields;
public List getFields(Object obj) {
Class c = obj.getClass();
// 获得类名
String className = obj.getClass().getSimpleName();
// 类名 + 前缀 = 表名
tableName = TABLE_PREFIX + className.toLowerCase();
// 获得所有的属性
fields = c.getDeclaredFields();
Method[] method = c.getMethods();
List list = new ArrayList();
for (int j = 0; j < fields.length; j++) {
String m = "get" + fields[j].getName().toUpperCase().charAt(0)
+ fields[j].getName().substring(1);
for (int i = 0; i < method.length; i++) {
if (method[i].getName().endsWith(m)) {
// method[i].invoke("", null);
try {
list.add(method[i].invoke(obj, null));
// System.out.println("---------"
// + method[i].invoke(obj, null));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
return list;
}
public String getInsertSQL(Object obj) {
// 拼SQL语句
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO ");
sql.append("" + tableName + "");
sql.append(" (");
for (int i = 0; i < fields.length; i++) {
sql.append("" + fields[i].getName() + "");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(") ");
sql.append(" VALUES(");
for (int i = 0; i < fields.length; i++) {
sql.append("?");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(") ");
return sql.toString();
}
public String getUpdateSQL(Object obj) {
// 拼SQL语句
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ");
sql.append("" + tableName + "");
sql.append(" SET ");
for (int i = 1; i < fields.length; i++) {
sql.append("" + fields[i].getName() + "");
sql.append("=?");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(" WHERE ");
sql.append(fields[0].getName());
sql.append("=?");
return sql.toString();
}
public String getSelectSQL(Object obj) {
// 拼SQL语句
StringBuffer sql = new StringBuffer();
sql.append("SELECT * FROM ");
sql.append("" + tableName + "");
return sql.toString();
}
public String getDeleteSQL(Object obj) {
// 拼SQL语句
StringBuffer sql = new StringBuffer();
sql.append("DELETE FROM ");
sql.append("" + tableName + "");
sql.append(" WHERE ");
sql.append(fields[0].getName());
sql.append("=?");
return sql.toString();
}
}