DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Top Book Picks for Site Reliability Engineers
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  1. DZone
  2. Data Engineering
  3. Databases
  4. My Favorite Spring Data JPA Feature

My Favorite Spring Data JPA Feature

I’m impressed by the complexity of query you can write using Spring Data. My favourite feature is returning the first or top records from a table.

By 
Martin Farrell user avatar
Martin Farrell
·
Jul. 01, 16 · Opinion
Likes (26)
Comment
Save
Tweet
Share
47.3K Views

Join the DZone community and get the full member experience.

Join For Free

I like Spring Data JPA. It helps simplify my codebase, and most of the time 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 feature is returning the first or top records from a table.

Let's say I have a table tracking document versions -

DOCUMENT_TABLE

DOCUMENT_IDNAMEVERSION
1mydoc.doc
1
2mydoc.doc2
3mydoc.doc3

With its associated JPA object -

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

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

   @Basic(optional = false)
   @NotNull
   private String name;

   @Basic(optional = false)
   @NotNull
   private Long version;

}

My SQL would be -

SELECT *
FROM
  (SELECT *
  FROM document_table dt
  WHERE dt.name = 'mydoc.doc'
  ORDER BY dt.VERSION DESC
  )
WHERE rownum = 1;

Or in JPA -

select d
   from Document d
   where d.name = :name
   and d.version = (select max(d.version) from Document d where d.name = :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 =
   documentRepository.findByNameOrderByVersionDesc("mydoc.doc");
Document document = documentList.get(0);

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 being equivalent

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

Document findTop2ByNameOrderByVersionDesc(String name);

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

Spring Data Data (computing) Spring Framework Database

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!