java - 如何将Resultset Jpa分配给Hashmap
问题描述
嗨,我在界面中有当前代码ComComuneRepository < extends JpaRepository>
@Query(value = "SELECT COM_PRG_PK, COM_DESCRIZIONE FROM com_comune ORDER BY
com_descrizione", nativeQuery = true)
HashMap <Long, String> findAllComuneIdAndDescrizione();
无论如何,它会引发错误,因为JPA
它不会自动理解我想将其分配Com_Prg_Pk
给 Long 和Com_Descrizione
String。
我怎样才能做到这一点JpaRepository
?
解决方案
从 JPA 2.2 版本开始,您可以使用 getResultStream 查询方法将 List 结果转换为 Map<Long, String>
Map<Long, String> findAllComuneIdAndDescrizione = entityManager.createQuery("""
SELECT COM_PRG_PK, COM_DESCRIZIONE FROM com_comune ORDER BY
com_descrizione
""", Tuple.class)
.getResultStream()
.collect(
Collectors.toMap(
tuple -> ((Long) tuple.get("COM_PRG_PK")).longValue(),
tuple -> ((String)tuple.get("COM_DESCRIZIONE")).stringValue()
)
);
或者...以下存储库类可能会给您一个想法
@Repository
public interface DBReportRepository extends JpaRepository<TransactionModel, Long> {
List<TransactionModel> findAll();
default Map<Long, TransactionModel> findAllMap() {
return findAll().stream().collect(Collectors.toMap(TransactionModel::getId, v -> v));
}
List<TransactionModel> findByClientId(Long id);
default Map<Long, TransactionModel> findByClientIdMap(Long id) {
return findByClientId(id).stream().collect(Collectors.toMap(TransactionModel::getId, v -> v));
}
}
推荐阅读
- javascript - 如何强制从运行在 HTTPS 上的前端发出 HTTP 请求?
- html - 反应错误刷新时在此服务器上找不到请求的URL
- asp.net-core - 如果在发布文件夹外执行 dotnet,dotnet 不会加载 appsettings.json
- typescript - 删除`··`,替换`············` 为`······` eslint() eslintprettier/prettier
- google-cloud-run - Cloud Run HTTP2 破坏了 CORS
- npm - npm 7 - 为什么在对 install 命令进行了所有改进之后我们还需要 ci 命令?
- c - 复制缓冲区并返回指向下一个可用元素的指针的最佳方法是什么?
- javascript - 如何使用 ref 访问和销毁画布?
- database - 我们可以包含存储在数据库中的 html 内容的部分视图#laravel
- javascript - 如何将一个div附加到另一个div中?