1

Based on question How to return a custom object from a Spring Data JPA GROUP BY query, my custom query is working, as follows:

@Query("select new br.com.cwidevs.dto.Goleador(j.id, sum(pj.gols)) from PartidaJogador pj join pj.id.jogador j group by j.id")
public List<Goleador> getGoleadores();

Here is the simple bean class:

public class Goleador {

    private Long jogador;

    private Long totalGols;    
}

At this point, how to implement ORDER BY? Can I achieve thi with Sort?

Community
  • 1
  • 1
Murillo Goulart
  • 154
  • 6
  • 22

3 Answers3

3

Try this:

@Entity
public class Goleador {
    //...
}

@Entity
public class PartidaJogador {
    //...

    @ManyToOne
    private Goleador jogador;

    private Long gols;

    //...
}

// DTO as Projection
public interface GoleadorWithGols {
    Goleador getGoleador();
    Long getTotalGols()
}

public interface GoleadorRepo extends JpaRepository<Goleador, Long> {
    @Query("select j as goleador, sum(pj.gols) as totalGols from PartidaJogador pj join pj.jogador j group by j order by totalGols")
    List<GoleadorWithGols> getGoleadores();
}

Here we use a projection GoleadorWithGols as DTO to get necessary data.

More info is here.

Cepr0
  • 28,144
  • 8
  • 75
  • 101
2

JpaRepository extends PagingAndSortingRepository so you can definetly use Sort

Add parameter to your method
public List<Goleador> getGoleadores(Sort sort);

when you call it just specify by which column you want to sort your query and you should be good.

repoGoleador.getGoleadores(new Sort("jogador"));  
Martin Čuka
  • 16,134
  • 4
  • 23
  • 49
0

I just solved this problem :

Class-based Projections doesn't work with query

native(@Query(value = "SELECT ...", nativeQuery = true))

So I recommend to define custom DTO using interface . Before using DTO should verify the query syntactically correct or not.

Yasen
  • 4,241
  • 1
  • 16
  • 25
Yousra ADDALI
  • 332
  • 1
  • 3
  • 14