select delete增强篇

private Class<?> clazz;
public BaseDao(){
    //this对应得是子类对象。获取当前反射类对象
    Class<? extends BaseDao> aClass = this.getClass();
    //获取当前反射得父类反射类    包含父亲得泛型
    ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
    //获取泛型的反射类
    Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
    clazz = (Class<?>) actualTypeArguments[0];
}
//查寻
public List<User> selectOne()throws Exception {
    Connection conn = null;
    PreparedStatement ps = null;
    List list = new ArrayList();
    StringBuffer sql = new StringBuffer("select * from ");
    //获取表名
    TableName annotation = clazz.getAnnotation(TableName.class);
    String value = "";
    if (annotation != null) {
        value = annotation.value();
    } else {
        value = clazz.getSimpleName();
    }
    sql.append(value);
    //允许访问本类下所有属性

    conn = DBUtils.getConn();
    ps = conn.prepareStatement(sql.toString());
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
       Object o = clazz.newInstance();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            TableField annotation2 = declaredField.getAnnotation(TableField.class);
            if (annotation2 == null) {
                declaredField.set(o, rs.getObject(declaredField.getName()));
            } else {
                declaredField.set(o, rs.getObject(annotation2.value()));
            }
        }
        list.add(o);
    }
    return list;
}
//删除
public int detele(int id) throws Exception{
    Connection conn=null;
    PreparedStatement ps=null;
    StringBuffer sql = new StringBuffer("delete from ");
    //获取表名
    TableName annotation = clazz.getAnnotation(TableName.class);
    String value = "";
    if (annotation != null) {
        value = annotation.value();
    } else {
        value = clazz.getSimpleName();
    }
    sql.append(value+" where ");
    Field ids = clazz.getDeclaredField("sid");
        //允许访问本类下所有属性
        ids.setAccessible(true);
        KeyTable annotation1 = ids.getAnnotation(KeyTable.class);
         sql.append(annotation1.value()+" = "+id);
    System.out.println(sql);
    conn = DBUtils.getConn();
    ps = conn.prepareStatement(sql.toString());
    int i = ps.executeUpdate();

    return i;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值