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

io.github.jinghui70.rainbow.dbaccess.object.BeanMapper Maven / Gradle / Ivy

There is a newer version: 5.2.1
Show newest version
package io.github.jinghui70.rainbow.dbaccess.object;

import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 支持数组属性的对象RowMapper
 *
 * @param  对象泛型
 */
public class BeanMapper implements RowMapper {

    private final Class mappedClass;
    private final Map propMap;

    private BeanMapper(Class mappedClass) {
        this.mappedClass = mappedClass;
        this.propMap = PropInfoCache.get(mappedClass);
    }

    BeanMapper(Class mappedClass, LinkedHashMap propMap) {
        this.mappedClass = mappedClass;
        this.propMap = propMap;
    }

    public static  BeanMapper of(Class clazz) {
        return new BeanMapper<>(clazz);
    }

    @Override
    public T mapRow(ResultSet rs, int rowNum) throws SQLException {
        T result = BeanUtils.instantiateClass(this.mappedClass);
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        for (int index = 1; index <= columnCount; index++) {
            String column = JdbcUtils.lookupColumnName(metaData, index);
            String field = StringUtils.delete(column, " ").toLowerCase();
            PropInfo propInfo = propMap.get(field);
            if (propInfo != null) {
                Object value = propInfo.getValue(rs, index);
                propInfo.setValue(result, value);
            }
        }
        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy