0

This query here is basically working as intended:

@Query("SELECT " +
       "   votedItem.groupVoting.id AS votingId, " +
       "   COUNT(votedItem) AS nbVotes " +
       "FROM VotingVotedItemEntity votedItem " +
       "WHERE votedItem.id IN :votingIds " +
       "GROUP BY votedItem.id, votedItem.item.id")
List<Object> findItemVoteCountsByVotingIds(@Param("votingIds") List<Long> votingIds);

My problem is I can't get the result into an object. The query is not final but in the end it should be mapped into a class:

public class ItemVotes 
{
    private String name;
    private Integer voteCount;
    /*  Getter & setter */
}

I don't know what the way to go is here. At this point I think I'd have to create it's own JpaRepository:

public interface VoteCountsRepository extends JpaRepository<ItemVotes, Long> {
}

but this does not work as the server dies on startup to a

IllegalArgumentException: Not a managed type

Can somebody explain to me how to map custom types into objects here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378

1 Answers1

0

You should be able to do something like this:

@Query("SELECT " +
       "   new package.of.class.ItemVotes(votedItem.groupVoting.id AS votingId, " +
       "   COUNT(votedItem) AS nbVotes) " +
       "FROM VotingVotedItemEntity votedItem " +
       "WHERE votedItem.id IN :votingIds " +
       "GROUP BY votedItem.id, votedItem.item.id")
List<ItemVotes> findItemVoteCountsByVotingIds(@Param("votingIds") List<Long> votingIds);

Called a JPQL constructor expression.

Dovmo
  • 8,121
  • 3
  • 30
  • 44
  • But does this require its own `JpaRepository` or should this work anywhere? – Stefan Falk Sep 14 '18 at 15:47
  • It will work anywhere. I think you'll likely want to put it in your `VotedItemRepository` since that data is indicative about counts of voted items... – Dovmo Sep 14 '18 at 15:56
  • Hmm. Okay this seems to work and there's no "nicer" way than this? It really makes me wonder why I use an ORM if I have to write queries which look like that :D – Stefan Falk Sep 14 '18 at 16:12
  • You could write your own custom [Hibernate query](https://github.com/spring-projects/spring-data-examples/tree/master/jpa/example/src/main/java/example/springdata/jpa/custom). But for what you're doing, this is definitely the cleanest way to do it. IMHO you didn't have to change the query drastically, and it's still much cleaner than writing a native query, doing joins, and creating some hibernate mapping or the like – Dovmo Sep 14 '18 at 16:19