javajpaspring-boot-jpa

Convert to DTO from join selection


I have these two tables

enter image description here

And I am using this query to get the results

@Query(value = "SELECT bet.bet, match.name, match.week FROM bet INNER JOIN match ON match.id=bet.match_id WHERE match.week = ?1", nativeQuery = true)
List<Object[]> customQuery(Long week);

So far this is the only way I could retrieve the results and actually use them later. To use them I am using this code currently

List<Object[]> bets = gr.customQuery(2l);
for (Object[] object : bets) {
    int bet = (BigInteger) object[0];
    String name = (String) object[1];
    int week = (BigInteger) object[2];

    System.out.println(bet + " " + name + " " + week);
}

But using it that way seems odd to me. Is there a better way to directly map the result to a DTO or something...


Solution

  • There are some options. The most straighforward way would be to define a projection Interface, like:

    public interface BetDTO {
        Long getBet();
        String getName();
        Integer getWeek();
    }
    

    With that you could change your query return type to:

    List<BetDTO> customQuery(Integer week);
    

    The rest would then be using getters.