javahibernatejparepository

return map in jpaRepository


I have a List of UUIDs that is fed into the method parameters in the repository. I need to return a Map<UUID, Boolean> map that will duplicate all the values from the list in the keys. If the value from list is present in entity.get Service Id(), then the value of map is set to true, otherwise false. How to do it?


Solution

  • If you're using spring-data-jpa then you could use the @Query annotation

    Without immediately going for a far more complex query, I'd recommend just querying the values that would result true and then construct the map based on that result.

    @Query("select ?1 from YourEntityHere yeh where yeh.id = ?1")
      List<Uuid> findServiceUuids(List<UUID> uuids);
    

    And then in the calling layer:

    private Map<UUID, Boolean> getMapUuidAndFoundStatus(List<UUID> uuids) {
            List<UUID> foundUuids = repository.findServiceUuids(uuids);
            return uuids.stream().collect(Collectors.toMap(Function.identity(), foundUuids::contains));
        }
    

    There is guaranteed a way to do it in one query without the accessing layer but it is very likely to reduce readability, performance and reusability.