[英]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:基于问题How to return a custom object from a Spring Data JPA GROUP BY query ,我的自定义查询正在运行,如下所示:
@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:这是简单的 bean 类:
public class Goleador {
private Long jogador;
private Long totalGols;
}
At this point, how to implement ORDER BY
?此时,如何实现ORDER BY
? Can I achieve thi with Sort ?我可以用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.这里我们使用投影GoleadorWithGols作为 DTO 来获取必要的数据。
JpaRepository extends PagingAndSortingRepository so you can definetly use Sort JpaRepository扩展了 PagingAndSortingRepository所以你可以明确地使用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基于类的Projections
不适用于查询
native(@Query(value = "SELECT ...", nativeQuery = true))
So I recommend to define custom DTO
using interface.所以我建议使用接口定义自定义DTO
。 Before using DTO
should verify the query syntactically correct or not.在使用DTO
之前应该验证查询在语法上是否正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.