目 录CONTENT

文章目录

动态规则查询返回Object类转化成DpoImport类, 逐步优化转为工具类

不争
2024-01-02 / 0 评论 / 0 点赞 / 86 阅读 / 11598 字

动态规则查询返回Object类转化成DpoImport类, 逐步优化转为工具类

1.这是默认返回的List列表,我们需要拿到里面的Value

2.默认返回Object对象

3.后端通过强制类型转换循环遍历转换的方法(过于繁琐)
    private List<DpoImport> convertToDpoImports(List<Map<String, Object>> items) {
        List<DpoImport> dpoImports = new ArrayList<>();

        for (Map<String, Object> item : items) {
            DpoImport dpoImport = new DpoImport();

            dpoImport.setId((Long) item.get("id"));
            dpoImport.setDonorId((String) item.get("donor_id"));
            dpoImport.setGiftId((String) item.get("gift_id"));
            dpoImport.setGiftDate((Timestamp) item.get("gift_date"));
            dpoImport.setGiftType((String) item.get("gift_type"));
            dpoImport.setBill((BigDecimal) item.get("bill"));
            dpoImport.setSolCode((String) item.get("sol_code"));
            dpoImport.setPkgCode((String) item.get("pkg_code"));
            dpoImport.setIncentive((String) item.get("incentive"));
            dpoImport.setTitle((String) item.get("title"));
            dpoImport.setFirstName((String) item.get("first_name"));
            dpoImport.setLastName((String) item.get("last_name"));
            dpoImport.setBirthday((Timestamp) item.get("birthday"));
            dpoImport.setCity((String) item.get("city"));
            dpoImport.setState((String) item.get("state"));
            dpoImport.setContactId((String) item.get("contact_id"));
            dpoImport.setContactDate((Timestamp) item.get("contact_date"));
            dpoImport.setActivityCode((String) item.get("activity_code"));
            dpoImport.setWelcomeSurveyResult((String) item.get("welcome_survey_result"));
            dpoImport.setNumberOfPledges((String) item.get("number_of_pledges"));
            dpoImport.setActivePledges((String) item.get("active_pledges"));
            dpoImport.setDayPledgeNumber((String) item.get("day_pledge_number"));
            dpoImport.setBank((String) item.get("bank"));
            dpoImport.setCampaign((String) item.get("campaign"));
            dpoImport.setByWhom((String) item.get("by_whom"));
            dpoImport.setStatus((String) item.get("status"));
            dpoImport.setContactNotes((String) item.get("contact_notes"));
            dpoImport.setTmresult((String) item.get("tm_result"));
            dpoImport.setTmFinishDate((String) item.get("tm_finish_date"));
            dpoImport.setBatchNo((String) item.get("batch_no"));
            dpoImport.setTmId((Long) item.get("tm_id"));
            dpoImport.setDistributeDate((Timestamp) item.get("distribute_date"));
            dpoImport.setDistributeStatus((Integer) item.get("distribute_status"));
            dpoImport.setDpoExportDate((Timestamp) item.get("dpo_export_date"));
            dpoImport.setCreatedBy((Long) item.get("created_by"));
            dpoImport.setCreatedAt((Timestamp) item.get("created_at"));
            dpoImport.setUpdatedBy((Long) item.get("updated_by"));
            dpoImport.setUpdatedAt((Timestamp) item.get("updated_at"));

            // 将转换后的 DpoImport 对象添加到列表中
            dpoImports.add(dpoImport);
        }

        return dpoImports;
    }

4.通过反射方式(后端是驼峰,数据库是小写+下划线)

反射赋值得时候需要进行驼峰转换,这里单独写了个函数进行调用(convertCamelCaseToUnderscore)

    private List<DpoImport> convertToDpoImports(List<Map<String, Object>> items) {
        List<DpoImport> dpoImports = new ArrayList<>();

        for (Map<String, Object> item : items) {
            DpoImport dpoImport = new DpoImport();
            Class<?> dpoImportClass = DpoImport.class;

            for (Field field : dpoImportClass.getDeclaredFields()) {
                String fieldName = field.getName();

                // 将驼峰形式的属性名转换为小写下划线形式的字段名
                String columnName = convertCamelCaseToUnderscore(fieldName);
                Object value = item.get(columnName);

                if (value != null) {
                    try {
                        field.setAccessible(true);
                        field.set(dpoImport, value);
                    } catch (IllegalAccessException ex) {
                        log.warn("convertToDpoImports", ex);
                    }
                }
            }

            dpoImports.add(dpoImport);
        }

        return dpoImports;
    }

    private String convertCamelCaseToUnderscore(String input) {
        StringBuilder sb = new StringBuilder();
        for (char c : input.toCharArray()) {
            if (Character.isUpperCase(c)) {
                sb.append('_').append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
5.终极版

既然都写到反射这个程度,不如调用的时候再传个泛型类,实现Object转N种对象

@Slf4j
public final class FieldNameConverterHelper {
    public static <T> List<T> convertToClass(List<Map<String, Object>> items, Class<T> clazz) {
        List<T> resultList = new ArrayList<>();

        for (Map<String, Object> item : items) {
            T instance;
            try {
                instance = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception ex) {
                log.warn("convertToClass", ex);
                continue;
            }

            for (Field field : clazz.getDeclaredFields()) {
                String fieldName = field.getName();

                String columnName = convertCamelCaseToUnderscore(fieldName);
                Object value = item.get(columnName);

                if (value != null) {
                    try {
                        field.setAccessible(true);
                        field.set(instance, value);
                    } catch (IllegalAccessException ex) {
                        log.warn("IllegalAccessException", ex);
                    }
                }
            }

            resultList.add(instance);
        }

        return resultList;
    }


    private static String convertCamelCaseToUnderscore(String input) {
        StringBuilder sb = new StringBuilder();
        for (char c : input.toCharArray()) {
            if (Character.isUpperCase(c)) {
                sb.append('_').append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

大功告成!

0

评论区