java 底层改写BaseDao

//查询通用方法
//运用泛型集合和list集合,参数放class泛型,SQL语句,和SQL语句里的参数
public List getAll(Class clz, String sql, Object… params) {
ResultSet rs = getRs(sql, params);

    List<T> datas = new ArrayList<>();

    ResultSetMetaData rsmd = null;// 获取列的信息 (列名, 数据类型);
    try {
        rsmd = rs.getMetaData();

        int columnCount = rsmd.getColumnCount();
        System.out.println("总共有:" + columnCount);


        if (rs != null) {
            //解析
            while (rs.next()) {
                // 使用反射
                T t = clz.newInstance();

// Question question = new Question();
// 获取实体类里的所有的set方法
List setMethod = EntityUtil.getAllSetMethod(clz);// 包括了 get
for (int i = 0; i < setMethod.size(); i++) {
String methodName = setMethod.get(i).getName();
for (int j = 0; j < columnCount; j++) {
String cLable = rsmd.getColumnLabel(j + 1);// 从1开始
String cType = rsmd.getColumnTypeName(j + 1);// Varchar
if (methodName.toUpperCase().endsWith(cLable.toUpperCase())) {
// System.out.println(cLable + “:” + cType + “:” + setMethod.get(i).getName() + “:” + EntityUtil.getColumn(cLable, cType, rs));
setMethod.get(i).invoke(t, EntityUtil.getColumn(cLable, cType, rs));
break;
}
}
}
datas.add(t);
}
}
return datas;
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
closeAll(conn, ps, rs);

    }
    return null;
}


public ResultSet getRs(String sql, Object... params) {
    conn = getConnection();
    ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(sql);
        // 添加参数
        if (params != null) {
        //解析SQL语句里的参数
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
        }

        rs = ps.executeQuery();

        return rs;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值