JdbcTemplate 结果封装对象

基于JdbcTemplate,将结果自动封装为对象,待优化

import org.springframework.jdbc.core.RowMapper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 可以自动填充的mapper
 *
 * @param 
 */
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);
    }


}

你可能感兴趣的:(java)