Murillo Goulart
Murillo Goulart

Reputation: 214

How to implement ORDER BY from a Spring Data JPA GROUP BY query

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?

Upvotes: 1

Views: 4791

Answers (3)

Yousra ADDALI
Yousra ADDALI

Reputation: 402

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.

Upvotes: 0

Cepr0
Cepr0

Reputation: 30289

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.

Upvotes: 3

Martin Čuka
Martin Čuka

Reputation: 18438

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"));  

Upvotes: 2

Related Questions