Apache 开源JDBC工具类库

Apache 开源JDBC工具类库Apache 开源JDBC工具类库

commons-dbutils jar下载

Apache 开源JDBC工具类库

Apache 开源JDBC工具类库

package com.jdbc.tools;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

public abstract class BasicDAOImpl2 <T> {
    //type代表T的实际类型
    private Class<T> type;
    private QueryRunner qr=new QueryRunner();

    //在创建子类对象时,一定会调用父类构造器,默认调用父类无参构造
    public  BasicDAOImpl2(){
        //this是正在new的对象
        //clazz就是正在new对象的那个子类的类型的Class对象
        Class<? extends BasicDAOImpl2> clazz = this.getClass();
        Type t=clazz.getGenericSuperclass();
        ParameterizedType pt=(ParameterizedType) t;
        Type[] types=pt.getActualTypeArguments();
        type= (Class) types[0];
    }

    public int update(String sql, Object...args) throws SQLException {
        return qr.update(JDBCToolsV3.getConnection(),sql,args);
    }
    public  T getBean(String sql, Object...args) throws SQLException {
        return  qr.query(JDBCToolsV3.getConnection(),sql,new BeanHandler<>(type),args);
    }
    public List<T> getBeanList(String sql, Object... args) throws SQLException {
        return  qr.query(JDBCToolsV3.getConnection(),sql,new BeanListHandler<>(type),args);
    }
}

相关推荐