package com.curtis.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class JdbcDaoImpl<T> implements DAO<T> {
private QueryRunner queryRunner = null;
private Class<T> clazz;
// 构造函数
@SuppressWarnings("unchecked")
public JdbcDaoImpl() {
queryRunner = new QueryRunner();
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superClass;
Type[] typeArgs = parameterizedType.getActualTypeArguments();
if (typeArgs != null && typeArgs.length > 0) {
if (typeArgs[0] instanceof Class) {
clazz = (Class<T>) typeArgs[0];
}
}
}
}
@Override
public void batch(Connection connection, String sql, Object[]... args)
throws SQLException {
queryRunner.batch(connection, sql, args);
}
@SuppressWarnings("unchecked")
@Override
public <E> E getValue(Connection connection, String sql, Object... args)
throws SQLException {
return (E) queryRunner
.query(connection, sql, new ScalarHandler(), args);
}
@Override
public List<T> getAllList(Connection connection, String sql, Object... args)
throws SQLException {
return queryRunner.query(connection, sql, new BeanListHandler<>(clazz),
args);
}
@Override
public T getOne(Connection connection, String sql, Object... args)
throws SQLException {
return queryRunner.query(connection, sql, new BeanHandler<>(clazz),
args);
}
@Override
public void update(Connection connection, String sql, Object... args)
throws SQLException {
queryRunner.update(connection, sql, args);
}
}