Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first row from a resultset with sort by descending using QueryDsl predicate and spring jpa

I am new to spring JPA . I have one query such that i've to get the resultset and take only the row at the top.I dont know how to do it in spring JPA.And i dont want it to be done using @Query annotation,Since i was asked not to go with any queries inside the code.This is the uery i want to convert

My Query

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 how my jpa repository looks like:

public ExampleTable findOne(MyPredicate.getLatest());

But this is'nt working out and i know it wont clearly.But I seriously dont know how to convert this above query.Can anyone help me out with this

like image 228
Deepak Ramakrishnan Kalidass Avatar asked Feb 14 '14 05:02

Deepak Ramakrishnan Kalidass


2 Answers

You can do it using just QueryDSL without Predicate and Repositories.

List<ExampleTable> examples = new JPAQuery()
                .from(QExampleTable.exampleTable)
                .limit(1)
                .orderBy(new OrderSpecifier<>(Order.DESC, QExampleTable.exampleTable.id))
                .list(QExampleTable.exampleTable);
like image 120
Rafael Rocha Avatar answered Nov 15 '22 07:11

Rafael Rocha


you can use offset or limit functions.

In your case .limit(1) should be enough

like image 23
Benjamin Fuentes Avatar answered Nov 15 '22 08:11

Benjamin Fuentes