简体   繁体   中英

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 ?

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM