How do you write a custom query in Spring Data JPA?

A custom query in Spring Data JPA is written by annotating a repository method with @Query and supplying either JPQL (querying against entity names and fields) or, with nativeQuery = true, raw SQL against actual table and column names.

Key Points

Example

Finding all users with a specific first name is a simple enough case for query derivation, but wrapping it in an explicit @Query with a named parameter makes the intent clear and gives room to extend the query with more conditions later without renaming the method.

public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT u FROM User u WHERE u.firstName = :firstName")
    List<User> findByFirstName(@Param("firstName") String firstName);
}

Interview Tip

A concise interview answer is

I annotate the repository method with @Query and write JPQL referencing the entity and its fields, binding parameters by name with @Param for clarity. If I need database-specific SQL or performance JPQL can't deliver, I set nativeQuery = true and write plain SQL instead, and add @Modifying if the query is a write operation.

Last updated: 11 November 2026

Previous question: What is the difference between CrudRepository and JpaRepository?

Next question: What is the purpose of save() method in CrudRepository?

More Spring Data JPA interview questions

All Spring Data JPA questions