首页 > 解决方案 > 如何将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_DescrizioneString。

我怎样才能做到这一点JpaRepository

标签: javasqlspringjpahashmap

解决方案


从 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));
    }
}

推荐阅读