【Java Web】DbUtils工具类 —— 简单封装JDBC通用增删改查方法

DbUtils工具类 —— 简单封装JDBC通用增删改查方法

    • db.properties
    • DbUtils.java
    • ReflectionUtils.java
    • 测试效果
    • 参考资料

  对jdbc进行了简单的封装,用到了java泛型和java 反射还有方法可变参数,增删改查执行完毕后自动关闭连接释放资源(以前经常忘记,导致服务器宕机),理论上任何项目都可以使用,有兴趣的朋友可以试试。

db.properties

数据库配置文件

# MySQL地址
url=jdbc:mysql://localhost:3306/web
# MySQL用户名
username=root
# MySQL密码
password=root
# MySQL驱动
driver=com.mysql.jdbc.Driver

DbUtils.java

数据库工具类

package utils;

import java.io.InputStream;
import java.sql.*;
import java.util.*;

/**
 * MySQL工具类
 *
 * @author hui
 * @date 2020/7/17 15:20
 */
public class DbUtils {

    /**
     * 获取数据库连接
     *
     * @return connection对象
     */
    public static Connection getConnection() {
        Connection connection = null;
        Properties properties = new Properties();
        InputStream in = DbUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(in);
            String url = properties.get("url").toString();
            String username = properties.get("username").toString();
            String password = properties.get("password").toString();
            String driver = properties.get("driver").toString();
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     *
     * @param connection        connection对象
     * @param preparedStatement preparedStatement对象
     * @param resultSet         resultSet对象
     */
    public static void release(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用查询
     *
     * @param classes 类
     * @param sql     sql语句
     * @param args    查询参数
     * @param      泛型
     * @return 泛型对象
     */
    public static <T> T query(Class<T> classes, String sql, Object... args) {
        T object = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        ResultSetMetaData resultSetMetaData;
        try {
            connection = DbUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            resultSetMetaData = resultSet.getMetaData();
            Map<String, Object> map = new HashMap<>(16);
            if (resultSet.next()) {
                for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
                    String columnname = resultSetMetaData.getColumnLabel(i + 1);
                    Object obj = resultSet.getObject(i + 1);
                    map.put(columnname, obj);
                }
            }
            if (map.size() > 0) {
                object = classes.newInstance();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String fieldName = entry.getKey();
                    Object value = entry.getValue();
                    ReflectionUtils.setFieldValue(object, fieldName, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.release(connection, preparedStatement, resultSet);

        }
        return object;
    }

    /**
     * 通用集合查询
     *
     * @param classes 类
     * @param sql     sql语句
     * @param args    查询参数
     * @param      泛型
     * @return 泛型集合
     */
    public static <T> List<T> list(Class<T> classes, String sql, Object... args) {
        List<T> objects = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        ResultSetMetaData resultSetMetaData;
        try {
            connection = DbUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            resultSetMetaData = resultSet.getMetaData();
            Map<String, Object> map = new HashMap<>(16);
            while (resultSet.next()) {
                T object = null;
                for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
                    String columnname = resultSetMetaData.getColumnLabel(i + 1);
                    Object obj = resultSet.getObject(i + 1);
                    map.put(columnname, obj);
                }
                if (map.size() > 0) {
                    object = classes.newInstance();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        String fieldName = entry.getKey();
                        Object value = entry.getValue();
                        ReflectionUtils.setFieldValue(object, fieldName, value);
                    }
                }
                objects.add(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.release(connection, preparedStatement, resultSet);

        }
        return objects;
    }

    /**
     * 通用插入
     *
     * @param sql  sql语句
     * @param args 查询参数
     * @return ture/fasle
     */
    public static boolean save(String sql, Object... args) {
        boolean state = true;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DbUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            preparedStatement.execute();
        } catch (Exception e) {
            state = false;
            e.printStackTrace();
        } finally {
            DbUtils.release(connection, preparedStatement, resultSet);
        }
        return state;
    }

    /**
     * 通用删除
     *
     * @param sql  sql语句
     * @param args 查询参数
     * @return ture/fasle
     */
    public static boolean remove(String sql, Object... args) {
        boolean state = true;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DbUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            preparedStatement.execute();
        } catch (Exception e) {
            state = false;
            e.printStackTrace();
        } finally {
            DbUtils.release(connection, preparedStatement, resultSet);
        }
        return state;
    }

    /**
     * 通用更新
     *
     * @param sql  sql语句
     * @param args 查询参数
     * @return ture/fasle
     */
    public static boolean update(String sql, Object... args) {
        boolean state = true;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = DbUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            preparedStatement.execute();
        } catch (Exception e) {
            state = false;
            e.printStackTrace();
        } finally {
            DbUtils.release(connection, preparedStatement, resultSet);
        }
        return state;
    }
}

ReflectionUtils.java

反射工具类

package utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author hui
 * @date 2020/7/17 15:50
 */
public class ReflectionUtils {
    /**
     * 通过反射,获得Class定义中声明的父类的泛型参数类型
     *
     * @param clazz 类
     * @return
     */
    public static <T> Class<T> getSuperGenericType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
     *
     * @param clazz 类
     * @param index 索引
     * @return 类
     */
    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getSuperclass();
        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];
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod
     *
     * @param object    类
     * @param fieldName 属性
     * @return 属性
     */
    public static Field getDeclaredField(Object object, String fieldName) {
        Field field;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                return field;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 设置参数
     *
     * @param object    对象
     * @param fieldName 属性
     * @param value     值
     */
    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = getDeclaredField(object, fieldName);
        assert field != null;
        field.setAccessible(true);
        try {
            field.set(object, value);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取参数
     *
     * @param object    对象
     * @param fieldName 属性
     * @return 值
     */
    public static Object getFieldValue(Object object, String fieldName) {
        Field field = getDeclaredField(object, fieldName);
        assert field != null;
        field.setAccessible(true);
        try {
            return field.get(object);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试效果

【Java Web】DbUtils工具类 —— 简单封装JDBC通用增删改查方法_第1张图片
【Java Web】DbUtils工具类 —— 简单封装JDBC通用增删改查方法_第2张图片

参考资料

https://blog.csdn.net/lw277232240/article/details/80465859
https://blog.csdn.net/Geek_sun/article/details/81296214

你可能感兴趣的:(Java,Web)