Social Media
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 –

 @Table(name = "DOCUMENT_TABLE")
 public class Document implements Serializable {
 private static final long serialVersionUID = 1L;

 @Column(name = "DOCUMENT_ID")
 private Long documentId;

@Basic(optional = false)
 private String name;

@Basic(optional = false)
 private Long version;


My SQL would be –

 FROM document_table dt
 WHERE = 'mydoc.doc'
 WHERE rownum = 1;

Or in JPA –

 select d
 from Document d
 where = :name
 and d.version = (select max(d.version) from Document d where = :name)

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

 public interface DocumentRepository extends CrudRepository<Document, Long> {
 List<Document> findByNameOrderByVersionDesc(String name);

I can get the first record –

List<Document> documentList =
 Document document = documentList.get(0);

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 –

public interface DocumentRepository extends CrudRepository<Document, Long> {
 Document findFirstByNameOrderByVersionDesc(String name);
 Document findTopByNameOrderByVersionDesc(String name);

The above methods are equivalent

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

Document findTop2ByNameOrderByVersionDesc(String name);

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

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment:

Add Your Reply