JDBC(1) : jdbc结果集封装成对象

 适用于对象的字段名和表的字段名相同的,以及对象字段为 createTime 表字段为 create_time

注意 : datetime字段不能转换为Date类型


import java.sql.ResultSet;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

/**
 * @Auther: liyue
 * @Date: 2018/12/7 17:01
 * @Description:
 */
public class ResulstToObjectUtil2 {

    /**
     * jdbc结果集封装成对象
     * 适用于对象的字段名和表的字段名相同的,以及对象字段为 createTime 表字段为 create_time
     *
     * @param rs
     * @param clazz
     * @param 
     * @return
     */
    public static  T rsToObject(ResultSet rs, Class clazz) {
        try {
            if (null == rs) {
                return null;
            }
            List names = getObjectAttributeNames(clazz);
            StringBuffer json = new StringBuffer();
            json.append("{");
            for (String name : names) {
                json.append("\"").append(name);
                String value = null;
                if (StringUtils.isBlank(value)) {
                    String newName = name = bigLetterToSmallAndBeforeAdd_(name);
                    try {
                        value = rs.getString(newName);
                    } catch (Exception e) {
                        value = "";
                    }
                }
                if (StringUtils.isBlank(value)) {
                    try {
                        value = rs.getString(name);
                    } catch (Exception e) {
                        value = "";
                    }
                }
                json.append("\":\"").append(value).append("\"").append(",");
            }
            json.delete(json.length() - 1, json.length());
            json.append("}");
            T t = JsonUtils.jsonToPojo(json.toString().replaceAll("null", ""), clazz);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    /**
     * 大写字母转小写并在该字母前面加_
     *
     * @param name
     * @return
     */
    private static String bigLetterToSmallAndBeforeAdd_(String name) {
        StringBuffer stringBuffer = new StringBuffer();
        char[] chars = name.toCharArray();
        for (char ch : chars) {
            boolean digit = Character.isUpperCase(ch);
            if (digit) {
                String str = String.valueOf(ch);
                String lstr = str.toLowerCase();
                stringBuffer.append("_");
                stringBuffer.append(lstr);
            } else {
                stringBuffer.append(ch);
            }
        }
        return stringBuffer.toString();
    }
}

依赖类/方法 : 

    getObjectAttributeNames()

    JsonUtils

       

 

END。    

你可能感兴趣的:(JDBC)