• JdbcTemplate 结果封装对象


    public class AutoRowMapper<T> implements RowMapper<T> {

    private static Map<String, Field[]> fields = new HashMap<>();

    private Class clazz;

    public AutoRowMapper(Class clazz) {
    this.clazz = clazz;
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) {
    try {
    T t = (T) clazz.newInstance();
    Field[] fs = getFields();
    for (int i = 0; i < fs.length; i++) {
    setValue(t, fs[i], rs.getObject(fs[i].getName()));
    }
    return t;
    } catch (InstantiationException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (SQLException e) {
    e.printStackTrace();
    }


    return null;
    }

    Field[] getFields() {
    if (null != fields.get(clazz.getName())) {
    return fields.get(clazz.getName());
    }
    List<Field> list = new ArrayList<>();
    Class c = clazz;
    while (c != Object.class) {
    Field[] declaredFields = c.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
    list.add(declaredFields[i]);
    }
    c = c.getSuperclass();
    }
    fields.put(clazz.getName(), list.toArray(new Field[list.size()]));
    return getFields();

    }

    void setValue(Object object, Field field, Object value) {
    String name = field.getName();
    try {
    Method method = clazz.getMethod(getMethodName(name), field.getType());
    method.invoke(object, value);
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    }
    }

    String getMethodName(String field) {
    return "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
    }


    }

  • 相关阅读:
    this用法
    break/continue的使用
    解决:sql server无法在C盘下创建database/操作系统错误5(拒绝访问)
    (转)科普:SATA、PCIe、AHCI、NVMe
    Java按位取反运算符“~”的工作原理
    <剑指offer> 第12题
    <剑指offer> 第11题
    <剑指offer> 第10题
    <剑指offer> 第9题
    <剑指offer> 第8题
  • 原文地址:https://www.cnblogs.com/JAYIT/p/12485449.html
Copyright © 2020-2023  润新知