Social Media

Category Archives for SQL

Photo by Lesly B. Juarez on Unsplash

Spring Data JPA – Top and First

I like Spring Data JPA. It helps simplify your codebase, and frees me up from writing JPAQL or SQL. I’m also impressed by the complexity of query you can write using Spring Data. My favourite Spring Data JPA feature is top and first, which returns the first or top records from a table

Spring Data JPA – Top and First

Lets say I have a table tracking document versions –


1 mydoc.doc 1
2 mydoc.doc 2
3 mydoc.doc 3

With its associated JPA object –

My SQL would be –

Or in JPA –

But I want to keep my codebase consistent so the first thing I can try is –

I can get the first record –

Thats Ok I guess. Another alternative is to have a straight SQL query in the repository, but the best option is to use the Top feature in spring data –

The above methods are equivalent

We can even use Top to return the top n records –

Interestingly the underlying SQL generated by Spring Data opts for the rownum construct I used in my original SQL statement