使用JDBC技术从数据库中查询出结果集然后要封装到实体对象中供jsp页面显示,当数据库字段比较多时,遍历起来很麻烦,所以写了如下工具方便使用,注:实体类的属性名必须和数据库的字段名一致才可以使用该工具。
public class BeanUtils {
private BeanUtils() {
}
/**
* @Description 将结果集封装成实体
* @param beanClass 实体字节码对象
* @param result 结果集
* @return 实体对象
* @throws Exception
*/
public static <T> T resultToBean(Class<T> beanClass, ResultSet result) throws Exception {
T instance = null;
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
ResultSetMetaData metaData = result.getMetaData();
if (result.next()) {
instance = beanClass.newInstance();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String label = metaData.getColumnLabel(i);
for (PropertyDescriptor property : descriptors) {
if (label.equals(property.getName())) {
change(instance, property, property.getWriteMethod(), result.getObject(label) + "");
}
}
}
}
return instance;
}
/**
* @Description 将结果集封装成实体集合
* @param beanClass 实体字节码对象
* @param result 结果集
* @return 实体集合
* @throws Exception
*/
public static <T> List<T> resultToList(Class<T> beanClass, ResultSet result) throws Exception {
List<T> list = new ArrayList<>();
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
ResultSetMetaData metaData = result.getMetaData();
while (result.next()) {
T instance = beanClass.newInstance();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String label = metaData.getColumnLabel(i);
for (PropertyDescriptor property : descriptors) {
if (label.equals(property.getName())) {
change(instance, property, property.getWriteMethod(), result.getObject(label) + "");
}
}
}
list.add(instance);
}
return list;
}
}