Java通过反射实现mysql数据库与Javabean对象的自动赋值(数据库字段要与Javabean对象的成员变量保持一致)

下面是该工具类

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 影佑佑
 *
 * 此方法要保证数据库字段与Javabean对象的成员变量名字一样
 *
 *
 * 此类包含的方法:
 *     1.更新操作
 *     2.查询操作:
 *        (1):查询结果为一个字段的一行(如总数量查询)
 *        (2):查询结果为一个集合
 *        (3):查询结果为一个JavaBean对象
 *
 */
public class BaseDao {

    /**
     * 更新(增加,删除,修改)操作通用方法
     */
    public static int upDate(String sql, List<Object> params){
        int row = 0;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //获得数据库连接
            connection = DBUtil.getConnection();
            //预编译
            preparedStatement = connection.prepareStatement(sql);
            //给?赋值
            if(params.size() > 0){
                for(int i = 0; i < params.size(); i++){
                    preparedStatement.setObject(i + 1, params.get(i));
                }
            }
            row = preparedStatement.executeUpdate();

        } catch (SQLException throwable) {
            throwable.printStackTrace();
        } finally {
            //关闭资源
            DBUtil.close(null,preparedStatement,connection);
        }

        return row;
    }

    /**
     *查询结果为一个字段的一行(如总数量查询)
     */
    public static Object findSingleValue(String sql,List<Object> params){
        Object value = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;

        try{
            //获取数据库连接
            connection = DBUtil.getConnection();
            //预编译
            preparedStatement = connection.prepareStatement(sql);
            //给?赋值
            if(params.size() > 0){
                for(int i = 0; i < params.size(); i++){
                    preparedStatement.setObject(i + 1, params.get(i));
                }
            }
            //给ResultSet赋值
            rs = preparedStatement.executeQuery();
            //判断并分析ResultSet结果集
            if(rs.next()){
                value = rs.getObject(1);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            DBUtil.close(rs,preparedStatement,connection);
        }
        return value;
    }

    /**
     * 查询结果为一个集合
     */
    public static List queryList(String sql,List<Object> params,Class c){
        List list = new ArrayList();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;

        try{
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            if(params.size() > 0){
                for(int i = 0; i < params.size(); i++){
                    preparedStatement.setObject(i + 1, params.get(i));
                }
            }
            //获取结果集对象
            rs = preparedStatement.executeQuery();
            //获取成员变量们以及数量
            Field[] fields = c.getDeclaredFields();
            int length = fields.length;
            //获取数据库的列名们,以及数量
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            //获取该类的构造器,用来创建对象
            Constructor constructor = c.getConstructor();
            while(rs.next()){
                Object o = constructor.newInstance();
                for(int i = 0;i < length; i++){
                    for(int j = 0;j < columnCount; j++){
                        String columnName = metaData.getColumnName(j+1);
                        if(columnName.equals(fields[i].getName())){
                            fields[i].setAccessible(true);
                            fields[i].set(o,rs.getObject(columnName));
                        }
                    }
                }
                list.add(o);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,preparedStatement,connection);
        }
        return list;
    }

    /**
     * 查询结果为一个JavaBean对象
     */
    public static Object querySingle(String sql,List<Object> params,Class c){
        Object bean = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;

        try{
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            if(params.size() > 0){
                for(int i = 0; i < params.size(); i++){
                    preparedStatement.setObject(i + 1, params.get(i));
                }
            }
            //获取结果集对象
            rs = preparedStatement.executeQuery();
            //获取成员变量们以及数量
            Field[] fields = c.getDeclaredFields();
            int length = fields.length;
            //获取数据库的列名们,以及数量
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            //获取该类的构造器,用来创建对象
            Constructor constructor = c.getConstructor();
            while(rs.next()){
                bean = constructor.newInstance();
                for(int i = 0;i < length; i++){
                    for(int j = 0;j < columnCount; j++){
                        String columnName = metaData.getColumnName(j+1);
                        if(columnName.equals(fields[i].getName())){
                            fields[i].setAccessible(true);
                            fields[i].set(bean,rs.getObject(columnName));
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,preparedStatement,connection);
        }
        return bean;
    }

}

下面是上面的工具类中用到的关闭资源,获取数据库链接的操作

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

/**
 *
 * @author lenovo
 */
public class DBUtil {

    private static Properties properties = new Properties();

    static {
        try {
            //加载资源
            InputStream in = DBUtil.class.getResourceAsStream("/db.properties");
            properties.load(in);
            //注册驱动
            Class.forName(properties.getProperty("JDBCNAME"));

        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得连接对象
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            //获取所需参数
            String URL = properties.getProperty("URL");
            String USER = properties.getProperty("USER");
            String PASSWORD = properties.getProperty("PASSWORD");
            //得到数据库连接
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭资源
     *
     * @param rs
     * @param ps
     * @param conn
     */
    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }

    }

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

影佑佑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值