java - 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úmero consultado (" + numero + ") ya pertenece a un Distrito de Tarificación.");
} else {
distrito.put("mensaje", "El número consultado (" + numero + ") no pertenece a un Distrito de Tarificación.");
}
return distrito;
}
解决方案
我不确定我做对了,所以如果这是错的,请原谅我,我只是想帮忙。
我认为您的代码的问题是您继续设置相同的 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úmero consultado (" + numero + ") ya pertenece a un Distrito de Tarificación.");
} else {
distrito.put("mensaje", "El número consultado (" + numero + ") no pertenece a un Distrito de Tarificación.");
}
我不懂西班牙语,所以很抱歉变量名,我希望意思清楚,反正只是问。
在您之前的代码中,您可能会得到错误的结果。
推荐阅读
- excel - 在文件夹中搜索与 Excel 范围内不同字符串匹配的文件
- sql-server - 交叉加入事实和维度
- python - 在 python 中查找幻数
- linux - 脚本:检测操作系统是 x32 还是 x64 位并下载最新的 Oracle Java JDK 8
- mongodb - { useUnifiedTopology: true } Pass 已弃用
- r - 美国各州 shapefile 的 R geom_point vs geom_line vs geom_path
- ruby-on-rails - 如何编写一个包装器 ruby 类来封装对 3rd 方 api 客户端的请求/响应?
- java - 从回收站视图中删除条目时出现问题
- wordpress - 审核网站 我的网页有指向 HTTP URL 的 HTTPS URL 链接
- c# - 使用 INotifyPropertyChanged 时防御重入和不变违规?