可以把不同表中的每一行数据,封装成不同类型的对象
注意/规范:
1.规定表中的列名必须和对象中的属性名相同
2.规定表中列名的类型必须和Java中的类型匹配
---------------------------------------------------------------------
BeanHandler:表示把结果集中的一行数据,封装成一个对象,专门针对结果集中只有一行数据的情况。
BeanListHandler:表示把结果集中的多行数据,封装成一个对象的集合,针对结果集中有多行数据。
-------------------------------------------------------------------------------------------------------
在handler包中新建BeanHandler类
public class BeanHandler<T> implements ResultSetHandler<T> { private Class<T> classType; //把结果集的一行数据封装成什么类型的对象 public BeanHandler(Class<T> classType) { this.classType=classType; } public T handle(ResultSet rs) throws Exception { //1)创建对应类的一个对象 T obj=classType.newInstance(); //2)取出结果集中当前光标所在行的某一列数据 BeanInfo beanInfo=Introspector.getBeanInfo(classType, Object.class); PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors(); if(rs.next()) { for(PropertyDescriptor pd:pds) { String columnName=pd.getName(); //获取对象的属性名,属性名和列名相同 Object val=rs.getObject(columnName); //3)调用该对象的setter方法,把某一列的数据设置进去 pd.getWriteMethod().invoke(obj, val); } } return obj; } }
如果一个类中的构造器是外界可以直接访问,同时没有参数,那么可以直接使用Class类中的newInstance方法创建对象
pubilc Object newInstance();相当于new 类名();
在Method类中有方法:
public Object invoke(Object obj,Object..args):表示调用当前Method锁表示的方法
参数: obj:表示被调用方法底层所属的对象 args:表示调用方法是传递的实际参数
返回:底层方法的返回结果
public Product get(Long id) { return JdbcTemplate.query("select * from product where id=?", new BeanHandler<>(Product.class),id); }
====================================================================
public class BeanListHandler<T> implements ResultSetHandler<List<T>>{ private Class<T> classType; public BeanListHandler(Class<T> classType) { this.classType=classType; } public List<T> handle(ResultSet rs) throws Exception { List<T> list=new ArrayList<>(); while(rs.next()) { T obj=classType.newInstance(); BeanInfo beanInfo=Introspector.getBeanInfo(classType, Object.class); PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors(); for(PropertyDescriptor pd:pds) { String columnName=pd.getName(); Object val=rs.getObject(columnName); pd.getWriteMethod().invoke(obj, val); } list.add(obj); } return list; } }
public List<Product> list() { return JdbcTemplate.query("select * from product",new BeanListHandler<>(Product.class)); }