分析一个最简单的框架流程
dbutil是我知的最简单的框架,分析它有利于了解框架的基础思路
select一个对象并返回是此框架最简单流程:
@Override public Admin selectAdminByUsername(String name) { Admin admin = null; QueryRunner queryRunner = new QueryRunner(); String sql = "select id,username,phone,password,salt from admin where username=?"; Connection connection = JdbcUtils.getConnection(); // todo BeanHandle??? BeanHandler<Admin> beanHandler = new BeanHandler<Admin>(Admin.class); try { admin = queryRunner.query(connection, sql, beanHandler, name); } catch (SQLException e) { System.out.println("adminDaoImpl_e_104"); e.printStackTrace(); } return admin; }
在以上代码段,创建了一个BeanHandler:BeanHandler<Admin> beanHandler = new BeanHandler<Admin>(Admin.class);
执行了sql:admin = queryRunner.query(connection, sql, beanHandler, name);
画图分析了sql执行的流程,以及此流程调用的method,是属于哪个类(BeanHandler的作用):
执行的最终,是靠BeanProcessor的tobean方法
public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException { PropertyDescriptor[] props = this.propertyDescriptors(type); ResultSetMetaData rsmd = rs.getMetaData(); int[] columnToProperty = this.mapColumnsToProperties(rsmd, props); return this.createBean(rs, type, props, columnToProperty); } this.createBean如下:
private <T> T createBean(ResultSet rs, Class<T> type, PropertyDescriptor[] props, int[] columnToProperty) throws SQLException { T bean = this.newInstance(type); for(int i = 1; i < columnToProperty.length; ++i) { if (columnToProperty[i] != -1) { PropertyDescriptor prop = props[columnToProperty[i]]; Class<?> propType = prop.getPropertyType(); Object value = this.processColumn(rs, i, propType); if (propType != null && value == null && propType.isPrimitive()) { value = primitiveDefaults.get(propType); } this.callSetter(bean, prop, value); } } return bean; }
断点调试:
每执行一次for循环:通过PropertyDescriptor prop,设置空参bean(反射instance创建)的一个子属性(根据rs)
最终返回处理好的bean