使用 QueryDsl 谓词和 spring jpa 通过降序从结果集中获取第一行

Dee*_*ass 5 spring predicate querydsl web spring-data-jpa

我是 spring JPA 的新手。我有一个查询,因此我必须获取结果集并仅获取顶部的行。我不知道如何在 spring JPA 中执行此操作。而且我不希望使用 @Query 注释来完成,因为我被问到不要在代码中进行任何查询。这是我想要转换的

我的查询

SELECT id,name FROM example_table ORDER BY id DESC LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

我在谓词文件中尝试了这样的事情:

public Predicate getLatest(){
 QExampleTable example = QExampleTable.exampleTable;
 return (Predicate) example.id.desc();     
}
Run Code Online (Sandbox Code Playgroud)

这就是我的 jpa 存储库的样子:

public ExampleTable findOne(MyPredicate.getLatest());
Run Code Online (Sandbox Code Playgroud)

但这行不通,我知道它不会清楚。但我真的不知道如何转换上面的查询。谁能帮我解决这个问题

Raf*_*cha 5

您可以仅使用 QueryDSL 来完成此操作,无需谓词和存储库。

List<ExampleTable> examples = new JPAQuery()
                .from(QExampleTable.exampleTable)
                .limit(1)
                .orderBy(new OrderSpecifier<>(Order.DESC, QExampleTable.exampleTable.id))
                .list(QExampleTable.exampleTable);
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 0

这不起作用,因为desc()返回必须与Query.orderBy()一起使用的OrderSpecifier

以下可以工作,尽管它不是“纯粹的”谓词:

public Predicate getLatest() {
  QExampleTable example = QExampleTable.exampleTable;
  return example.id.eq(new JPASubQuery().from(example).unique(example.id.max()));
}
Run Code Online (Sandbox Code Playgroud)

恐怕更干净的解决方案是您提供CustomRepository + 实现。