Getting the first row from a result set in descending order using the predicate QueryDsl and spring jpa

I am new to spring JPA. I have one query, so I have to get a result set and take only the line at the top. I do not know how to do this in spring JPA. And I don't want this to be done using the @Query annotation, since I was asked not to go with any queries inside the code. This is the uery I want to convert

My request

SELECT id,name FROM example_table ORDER BY id DESC LIMIT 1;

I tried something like this in my predicate file:

public Predicate getLatest(){
 QExampleTable example = QExampleTable.exampleTable;
 return (Predicate) example.id.desc();     
}

and this is what my jpa repository looks like:

public ExampleTable findOne(MyPredicate.getLatest());

But this does not work, and I know that it is not clear. But I seriously don’t know how to convert this above request. Can anyone help me with this

+3
source share
3

, QueryDSL Predicate Repositories.

List<ExampleTable> examples = new JPAQuery()
                .from(QExampleTable.exampleTable)
                .limit(1)
                .orderBy(new OrderSpecifier<>(Order.DESC, QExampleTable.exampleTable.id))
                .list(QExampleTable.exampleTable);
+2

.

.limit(1)

+1

This will not work because it desc()returns the OrderSpecifier to be used with Query.orderBy () .

The following may work, although this is not a "clean" predicate:

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

I am afraid that a cleaner solution is that you provide a CustomRepository + implementation.

0
source

All Articles