Queries

Spring Data JPA also provides options to write custom queries. The following snippet shows a simple example:

    @Query("select u from User u where u.name = ?1")    List<User> findUsersByNameUsingQuery(String name);

Important things to note are as follows:

  • @Query: The annotation to define queries for repository methods
  • select u from User u where u.name = ?1: Query to be executed. ?1 represents the first parameter
  • findUsersByNameUsingQuery: When this method is called, the query specified is executed with the name as the parameter

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.