All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mario6.common.db.mapper.BeanRowMapper Maven / Gradle / Ivy

The newest version!
package com.mario6.common.db.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

/**
 * 通过反射获得对应POJO对象
 *
 * 注:反射对象类型必须拥有一个默认构造函数
 * @param 
 */
public class BeanRowMapper implements RowMapper {

    private boolean snake;
    private Class beanClazz;

    private BeanRowMapper(Class beanClazz, boolean snake) {
        this.beanClazz = beanClazz;
        this.snake = snake;
    }

    public static  BeanRowMapper newInstance(Class clazz, boolean snake) {
        return new BeanRowMapper(clazz, snake);
    }

    public static  BeanRowMapper newInstantce(Class clazz) {
        return new BeanRowMapper(clazz,false);
    }


    @Override
    public T rowMap(ResultSet rs) throws SQLException {
        ClassInfo classInfo = ClassInfo.newInstance(beanClazz, false);
        List.FieldInfo> fields = classInfo.getFieldsInfo();
        T obj = classInfo.createByDefaultConstructor();

        for (ClassInfo.FieldInfo field : fields) {
            String column = field.getName(snake);
            Class type = convertType(field.getType());
            Object value = rs.getObject(column, type);
            field.setValue(obj, value);
        }
        return obj;
    }

    private Class convertType(Class orig) {
        Class type = orig;
        if(type == java.util.Date.class) {
            type = Timestamp.class;
        }
        return type;
    }
};




© 2015 - 2024 Weber Informatics LLC | Privacy Policy