分析
结果集处理
接口
public interface ResultSetHandle<T> {
public T resultHandle(ResultSet re);
}
实现类
public class BeanHandle<T> implements ResultSetHandle<List<T>>{
private Class<T> classType;
public BeanHandle(Class<T> classType) {
this.classType = classType;
}
@Override
public List<T> resultHandle(ResultSet re){
List<T> list = new ArrayList<>();
try {
while(re.next()) {
T obj = classType.newInstance();
BeanInfo bean = Introspector.getBeanInfo(classType,Object.class);
PropertyDescriptor[] pds = bean.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {// 遍历传入的字节码类中的属性
Object value = re.getObject(pd.getName());// 每个属性得到名字,即获得列名
pd.getWriteMethod().invoke(obj, value);// 直接调用这个属性的set方法设置值
}
list.add(obj);
}
}catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
StuDaoImp
public class StudentDAO implements DAO {
/* 省略了其他方法
RunSQL的query方法中需要传入结果集处理器
并且不同的DAO实现类就会写上不同类型,和字节码
这样就可以交给query统一解决
*/
@Override
public List<Student> get(int id) {
String sql = "select * from student where id = ?";
return RunSQL.query(sql, new BeanHandle<Student>(Student.class) , id);
}
@Override
public List<Student> getAll() {
String sql = "select * from student";
return RunSQL.query(sql, new BeanHandle<Student>(Student.class));
}
}
RunSQL
对于它的query方法
public static <T>T query(String sql,ResultSetHandle<T> result ,Object...x) {
Connection con = null;
PreparedStatement sta = null;
ResultSet re = null;
List<T> handleResult = new ArrayList<>();
try {
con = Database.getConnection();
sta = con.prepareStatement(sql);
for(int i = 0; i < x.length; i++) {
sta.setObject(i+1,x[i]);
}
re = sta.executeQuery();
return result.resultHandle(re);
}catch (Exception e) {
e.printStackTrace();
}finally {
Database.close(con, sta, re);
}
return null;
}