JDBCTool(JDBCTools的更新版,cp30版本)
作者:互联网
package DAO;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/*
* 与JDBCTools不同点:少了很多注释,少了很多落后的方法(Statement),更新和查询操作使用了连接池技术,优化了速度。
* 同时因为连接池技术,不用频繁关闭连接,但仍然提供了关闭连接的方法
*/
public class JDBCTool {
private static Connection connection=getConnection(); //使用单例模式,每个用户使用一个自己的连接
//开始事务
public static void begin(Connection connection) {
try {
connection.setAutoCommit(false);
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//提交事务
public static void commit(Connection connection) {
try {
connection.commit();
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//回滚事务
public static void rollback(Connection connection) {
try {
connection.rollback();
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//获取连接方法(从连接池里获取连接)
public static Connection getConnection() {
try {
connection=new ComboPooledDataSource().getConnection();
return connection;
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//关闭连接方法
//关闭俩个对象方法
public static void release(Connection connection,Statement statement) {
try {
if(connection!=null) {
connection.close();
}
if(statement!=null) {
statement.close();
}
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//关闭三个对象方法
public static void release(Connection connection,Statement statement,ResultSet resultset) {
try{
if(connection!=null) {
connection.close();
}
if(statement!=null) {
statement.close();
}
if(resultset!=null) {
resultset.close();
}
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//执行sql插入、删除或更新的通用方法(利用PreparedStatement)
public static void Update(String sql,Object ... obj) {//Object ... agrs表示一个参数列表(Object数组),
//可以为任意类型,任意个数
try{
PreparedStatement preparedstatement=connection.prepareStatement(sql);
if(obj!=null){
for(int i=0;i<obj.length;i++) {
preparedstatement.setObject(i+1,obj[i]);
}
}
preparedstatement.executeUpdate();
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//执行sql查询的通用方法(利用PreparedStatement)
public static ResultSet Select(String sql,Object ...obj) {
try{
PreparedStatement preparedstatement=connection.prepareStatement(sql);
if(obj!=null){
for(int i=0;i<obj.length;i++) {
preparedstatement.setObject(i+1,obj[i]);
}
}
return preparedstatement.executeQuery();
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//查询一条记录
//传入SQL查询语句和类,返回一个与其一一对应属性的类
//即返回一个记录类
public static <T> T get(Class<T> clazz,String sql,Object ...obj) {
try{
T Record=null;
ResultSet resultset=Select(sql,obj);
if(resultset.next()) { //如果查询结果不为空
Record=clazz.newInstance(); //实例化对象
ResultSetMetaData resultsetmetadata=resultset.getMetaData();
Map<String,Object>map=new HashMap<String, Object>();
for(int i=0;i<resultsetmetadata.getColumnCount();i++) {
map.put(resultsetmetadata.getColumnName(i+1),resultset.getObject(i+1));
}
for(Map.Entry<String,Object> entry:map.entrySet()) { //取出map里每条记录entry(Key-Value)
ReflectionUtils.setFieldValue(Record, entry.getKey(),entry.getValue());
}
}
return Record;
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//查询多条记录,返回记录对象的列表
public static <T> List<T> getList(Class<T> clazz,String sql,Object ...obj) throws Exception{
ResultSet resultset=Select(sql,obj);
List<T> list=ListMap_To_List(clazz,Result_To_ListMap(resultset));
return list;
}
//传入ResultSet得到一个记录对象列表(List<Map<String,Object>>类型,Map的键为列名,值为列值)
public static List<Map<String, Object>> Result_To_ListMap(ResultSet resultset){
try{
List<Map<String,Object>> list=null;
ResultSetMetaData resultsetmetadata=resultset.getMetaData();
int columnCount=resultsetmetadata.getColumnCount();
ArrayList<String>columnName=new ArrayList<String>();
for(int i=0;i<columnCount;i++) {
columnName.add(resultsetmetadata.getColumnName(i+1));
}
list=new ArrayList<Map<String, Object>>();
while(resultset.next()) {
Map<String,Object>map=new HashMap<String, Object>();
for(int i=0;i<columnCount;i++) {
map.put(columnName.get(i),resultset.getObject(i+1));
}
list.add(map);
}
return list;
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//传入一个ListMap和记录对象类型获得一个对象列表List
public static <T> List<T> ListMap_To_List(Class<T> clazz, List<Map<String, Object>> listMap)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
List<T> list=null;
T Record=null;
if(listMap.size()>0) {
list=new ArrayList<T>();
for(Map<String,Object>map:listMap) { //取出listMap里每个map对象
Record=clazz.newInstance();
for(Map.Entry<String,Object>entry:map.entrySet()) {//取出map里的每个记录(entry:Key-Value)对象
ReflectionUtils.setFieldValue(Record,entry.getKey(),entry.getValue());
}
list.add(Record);
}
}
return list;
}
//返回某条记录的某一字段的值或一个统计的值(一共有多少条记录等)
public static <E> E getForValue(String sql,Object ...obj) {
try{
ResultSet resultset=Select(sql,obj);
resultset.next();
return (E) resultset.getObject(1);
} catch (Exception e) {
//运行时抛出异常
throw new RuntimeException(e);
}
}
//批量处理SQL语句(返回的Connection可用来进行事务处理)
public static void BatchSQL(String sql,int count,Object ...obj) throws Exception{
try {
begin(connection);
PreparedStatement preparedstatement=connection.prepareStatement(sql);
for(int i=0;i<obj.length;i++) {
preparedstatement.setObject(i+1,obj[i]);
}
for(int i=0;i<count;i++) {
preparedstatement.addBatch(); //积攒sql语句
}
preparedstatement.executeBatch(); //发送sql语句
preparedstatement.clearBatch(); //清空sql语句
commit(connection);
}catch(Exception e) {
rollback(connection);
e.printStackTrace();
}
}
//批量处理不同SQL语句(即处理相同Bean结构但数值不同的SQL语句)(返回的Connection可用来进行事务处理)
public static void BatchSQL(String sql,Object[][]obj){
try {
begin(connection);
PreparedStatement preparedstatement=connection.prepareStatement(sql);
for(int i=0;i<obj.length;i++) {
for(int j=0;j<obj[i].length;j++){
preparedstatement.setObject(j+1,obj[i][j]);
}
preparedstatement.addBatch(); //积攒sql语句
}
preparedstatement.executeBatch(); //发送sql语句
preparedstatement.clearBatch(); //清空sql语句
commit(connection);
}catch(Exception e) {
rollback(connection);
e.printStackTrace();
}
}
}
/**
* 反射的 Utils 函数集合
* 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
* @author Administrator
*
*/
class ReflectionUtils {
/**
* 将反射时的 "检查异常" 转换为 "运行时异常"
* @return
*/
public static IllegalArgumentException convertToUncheckedException(Exception ex){
if(ex instanceof IllegalAccessException || ex instanceof IllegalArgumentException
|| ex instanceof NoSuchMethodException){
throw new IllegalArgumentException("反射异常", ex);
}else{
throw new IllegalArgumentException(ex);
}
}
/**
* 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param clazz
* @param index
* @return
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index){
Type genType = clazz.getGenericSuperclass();
if(!(genType instanceof ParameterizedType)){
return Object.class;
}
Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
if(index >= params.length || index < 0){
return Object.class;
}
if(!(params[index] instanceof Class)){
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
* 如: public EmployeeDao extends BaseDao<Employee, String>
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static<T> Class<T> getSuperGenericType(Class clazz){
return getSuperClassGenricType(clazz, 0);
}
/**
* 循环向上转型, 获取对象的 DeclaredMethod
* @param object
* @param methodName
* @param parameterTypes
* @return
*/
public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
//superClass.getMethod(methodName, parameterTypes);
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
//Method 不在当前类定义, 继续向上转型
}
//..
}
return null;
}
/**
* 使 filed 变为可访问
* @param field
*/
public static void makeAccessible(Field field){
if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}
/**
* 循环向上转型, 获取对象的 DeclaredField
* @param object
* @param filedName
* @return
*/
public static Field getDeclaredField(Object object, String filedName){
for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
try {
return superClass.getDeclaredField(filedName);
} catch (NoSuchFieldException e) {
//Field 不在当前类定义, 继续向上转型
}
}
return null;
}
/**
* 直接调用对象方法, 而忽略修饰符(private, protected)
* @param object
* @param methodName
* @param parameterTypes
* @param parameters
* @return
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
Object [] parameters) throws InvocationTargetException{
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if(method == null){
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch(IllegalAccessException e) {}
return null;
}
/**
* 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
* @param object
* @param fieldName
* @param value
*/
public static void setFieldValue(Object object, String fieldName, Object value){
Field field = getDeclaredField(object, fieldName);
if (field == null){
//throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
}else{
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {}
}
}
/**
* 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
* @param object
* @param fieldName
* @return
*/
public static Object getFieldValue(Object object, String fieldName){
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {}
return result;
}
}
标签:object,return,JDBCTool,Object,param,更新版,static,cp30,public 来源: https://blog.csdn.net/qq_38487155/article/details/82531915