,java,spring,spring-boot"/>

首页 > 解决方案 > Oracle 查询返回为 Hasmap

问题描述

我正在对 Oracle 数据库进行此查询 SELECT T109.DISTRITO FROM T109 T109 ,其中 DISTRITO 列有很多数字。我想获取所有这些数字并将它们放在一个端点中,因此当他们使用它时,以 Hashmap 或 Hasmap 等格式显示此信息......但始终作为 Hashmap。我该怎么做?请忽略西班牙语单词,我知道我们必须始终用英文编码,但这是继承的代码。这是我尝试过的。

代码

private final String CONSULTA_SOLO_DISTRITOS =
            " SELECT T109.DISTRITO  \n"
                    + " FROM T109 T109 \n";


 public HashMap<String, String> getOnlyDistritoTarificacion(String numero) {

        List<Map<String, Object>> filas_distritos = null;

        HashMap<String, String> distrito = new HashMap();

        filas_distritos = jdbcTemplate.queryForList(CONSULTA_SOLO_DISTRITOS, new Object[]{numero, numero});

        if ((filas_distritos != null) && (!filas_distritos.isEmpty()) || (filas_distritos.size() != 0)) {

            Map<String, Object> row = filas_distritos.get(0);

            distrito.put("distrito", (String) row.get("DISTRITO"));

            distrito.put("mensaje", "El n&uacute;mero consultado (" + numero + ") ya pertenece a un Distrito de Tarificaci&oacute;n.");

        } else {

            distrito.put("mensaje", "El n&uacute;mero consultado (" + numero + ") no pertenece a un Distrito de Tarificaci&oacute;n.");

        }

        return distrito;

    }

标签: javaspringspring-boot

解决方案


我不确定我做对了,所以如果这是错的,请原谅我,我只是想帮忙。

我认为您的代码的问题是您继续设置相同的 Map 键分布,每个数字都来自查询 ResultSet。

相反,您应该在 List 对象中收集您的值,并在您分配它们时将值设置为您的 Map。

public HashMap<String, String> getOnlyDistritoTarificacion(String numero) {

    List<String> distritos = new ArrayList();

    HashMap<String, String> distrito = new HashMap();

    List<Map<String, Object>> filas_distritos = jdbcTemplate.queryForList(CONSULTA_SOLO_DISTRITOS, new Object[]{numero, numero});

    if ((filas_distritos != null) && (!filas_distritos.isEmpty()) || (filas_distritos.size() != 0)) {

        Map<String, Object> row = filas_distritos.get(0);

        distritos.add((String) row.get("DISTRITO"));
        distritos.put("distrito", (String) row.get("DISTRITO"));

    }

    distrito.put("distrito", 
                 distritos.stream()
                 .collect(Collectors.joining(","));

    return distrito;
}

因此,如您所见,您只需在收集完所有值后添加一次。我使用“,”来连接,但您可以使用您需要的其他字符或字符串。

此外,您不需要在每次迭代中添加“mensaje”的值,只需检查您需要设置的值:

boolean numberConsulted = true;

if ((filas_distritos != null) && (!filas_distritos.isEmpty()) || (filas_distritos.size() != 0)) {
    // .... code ...
} else {
    numberConsulted = false;
}


if (numberConsulted) {
    distrito.put("mensaje", "El n&uacute;mero consultado (" + numero + ") ya pertenece a un Distrito de Tarificaci&oacute;n.");
} else {
    distrito.put("mensaje", "El n&uacute;mero consultado (" + numero + ") no pertenece a un Distrito de Tarificaci&oacute;n.");
}

我不懂西班牙语,所以很抱歉变量名,我希望意思清楚,反正只是问。

在您之前的代码中,您可能会得到错误的结果。


推荐阅读