如何在querydsl中使用rownum

时间:2020-07-21 19:47:00

标签: mysql querydsl

enter image description here

enter image description here

在上述情况下如何使用rownum?

数据库:Mysql

plz ...

1 个答案:

答案 0 :(得分:0)

SqlExpressions.rowNumber()返回一个ROW_NUMBER()表达式。请记住,这仅适用于querydsl-sql而不适用于querydsl-jpa,因为JPQL(JPA的查询语言)本身缺乏对窗口函数的支持(专有JPQL扩展也是如此,例如Hibernates HQL)。

为了在JPA查询中使用ROW_NUMBER,必须为您的ORM提供者注册一个自定义函数。您可以使用custom functions自己注册这些功能。

注册自定义函数后,您仍将必须扩展JPQLTemplates以包括自定义窗口函数的模板。

您将这样做:

public class MyTemplates extends JPQLTemplates {

    public MyTemplates() {
        add(SQLOps.ROWNUMBER, "ROW_NUMBER({0})");
    }

}

然后按如下所示使用它:

new JPAQuery(entityManager, new MyTemplates()).from(entity).select(rowNumber())

但是,由于中间有Spring集成,所以将模板绑定到我认为更难的查询。


或者,您可以查看blaze-persistence-querydsl扩展名,该扩展名对JPQL的窗口功能(以及许多其他功能)具有开箱即用的支持。例如:

QCat cat = QCat.cat;

BlazeJPAQuery<Tuple> query = new BlazeJPAQuery<Tuple>(entityManager, criteriaBuilderFactory).from(cat)
    .select(cat.name, JPQLNextExpressions.rowNumber(), JPQLNextExpressions.lastValue(cat.name).over().partitionBy(cat.id));

List<Tuple> fetch = query.fetch();
相关问题