Thursday, 26 February 2026

JPA Repository's Magic - The Query methods and Query Annotations Basics

 Spring Data JPA is a framework which simplifies database interactions in Spring based applications and makes it easy to implement JPA(Java Persistent API) based repositories. It features pagination and sorting support allowing to fetch data in chunks instead of loading a large chunk of rows into memory at once. It helps reduce boilerplate code and simplified integration.

Here are some common inbuilt functions where no implementation code is required:

  • save(S entity) - Saves or updates a given entity.
  • findById(ID id) - Retrieves an entity by its primary key
  • findAll() - Returns a List of all entities in the table
  • deleteById(ID id) - Deletes the entity with the given ID
  • count() - Returns the total number of records
  • existsById(ID id) - Returns a boolean if the ID exists
  1. Query methods: They are a set of cool APIs where it simply requires to name the methods by following a naming convention and JPA parses the name of the method to generate SQL query to users:
  • findByNameContaining(String keyword) (Acts like a SQL LIKE %keyword%)
  • findByEmailAndStatus(String email, String status)
  • findAllByOrderByCreatedAtDesc()
    2. @Query Annotation(JPQL/ Native): When there is a complex logic and using query method                 names gets longer, the @Query annotation comes into play.
  • JPQL Example: @Query("SELECT u FROM User u WHERE u.email = :email") 
  • User fetchByEmailCustom(String email);
  • Native SQL Example @Query(value = "SELECT * FROM users WHERE active = true", nativeQuery = true)
  • List<User> findAllActiveUsersNative();

No comments:

Post a Comment