public class BaseDAO<T> {
private QueryRunner queryRunner = null;
private Class<T> type = null;
/**
* 实例化queryRunner而且获取BaseDAO的泛型类型
*/
@SuppressWarnings("unchecked")
public BaseDAO() {
// TODO Auto-generated constructor stub
queryRunner = new QueryRunner();
Type superType = getClass().getGenericSuperclass();
if(superType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) superType).getActualTypeArguments();
if(actualTypeArguments[0] instanceof Class){
type = (Class<T>) actualTypeArguments[0];
}
}
}
/**
* 通过sql的内容进行对应的增删改操作
*
* @param sql
* @param params
*/
public void update(String sql,Object...params){
Connection conn = JDBCUtil.getConn();
try {
queryRunner.update(conn, sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.release(conn);
}
}
/**
* 查询某个值,或者某列
* @param sql
* @param params
*/
@SuppressWarnings("unchecked")
public <E>E getForValue(String sql,Object...params){
Connection conn = JDBCUtil.getConn();
try {
return (E) queryRunner.query(conn, sql, new ScalarHandler(), params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.release(conn);
}
return null;
}
/**
* 返回某个实例对象
* @param sql
* @param params
* @return
*/
public T getForSingleObject(String sql,Object...params){
Connection conn = JDBCUtil.getConn();
try {
return queryRunner.query(conn, sql, new BeanHandler<T>(type), params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.release(conn);
}
return null;
}
/**
* 返回一个对象集合
* @param sql
* @param params
* @return
*/
public List<T> getForList(String sql,Object...params){
Connection conn = JDBCUtil.getConn();
try {
return queryRunner.query(conn, sql, new BeanListHandler<T>(type), params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.release(conn);
}
return null;
}
}