0

Hi I have the current code in interface ComComuneRepository < extends JpaRepository>

@Query(value = "SELECT COM_PRG_PK, COM_DESCRIZIONE FROM com_comune  ORDER BY 
                    com_descrizione", nativeQuery = true)
HashMap <Long, String> findAllComuneIdAndDescrizione();

Anyway, it throws errors since JPA doesn't automatically understand that I want to assign the Com_Prg_Pk to Long and Com_Descrizione to String.

How can I do that using JpaRepository?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
  • Does this answer your question? [How to return HashMap from JPA query?](https://stackoverflow.com/questions/31823778/how-to-return-hashmap-from-jpa-query) – İsmail Y. Sep 21 '21 at 21:07
  • @İsmail Y. I tried this approach, but what blocked me was that I didn't understand how to properly initialize EntityManager, since I'm using JPA , and not standard Dao – ucciucciBoh Sep 22 '21 at 08:25
  • You can actually do what you want to do in a simple and understandable way, as in the reference. Just replace `SELECT COM_PRG_PK, COM_DESCRIZIONE FROM com_comune ...` with `SELECT new map(c.COM_PRG_PK, c.COM_DESCRIZIONE) FROM com_comune c ORDER BY c.com_descrizione`. – İsmail Y. Sep 22 '21 at 08:51

1 Answers1

0

Since the JPA 2.2 version, you can use the getResultStream Query method to transform the List result into a 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()
    )
);

OR... the following repository class might give you an idea

@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));
    }
}
TanvirChowdhury
  • 2,498
  • 23
  • 28