Write a custom query in Spring 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: • JPQL queries operate on entity object graphs, so they reference the entity class name and its field names rather than the underlying table/column names. • Named parameters, bound with @Param("name") on the method argument, keep the query readable and resistant to reordering bugs compared to positional (?1, ?2) parameters. • nativeQuery = true is used when you need database-specific SQL functions or performance characteristics that JPQL can't express. • @Query methods that modify data (UPDATE/DELETE) additionally require @Modifying and usually @Transactional.

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.

Code Example:

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."