![]() |
VOOZH | about |
Spring Data JPA simplifies database interactions by eliminating boilerplate code. Its findBy methods allow developers to define queries using intuitive method names in repository interfaces. Spring Data JPA automatically interprets these method names and generates corresponding SQL queries.
The findBy method follows the pattern: findBy + PropertyName [+ Condition] [+ OrderBy]. Spring interprets the method name and executes the query.
Suppose we want to fetch books by an author published after a specific year, sorted by title.
Next, we will define the complex query in our repository interface.
Spring Data JPA supports various keywords to create complex queries directly from method names.
Combine multiple conditions
List<Book> findByAuthorAndPublishedYear(String author, int year);
Match any one of multiple conditions
List<Book> findByAuthorOrTitle(String author, String title);
Suitable for complex Queries
List<Book> findByAuthorAndPublishedYearOrTitle(String author, int year, String title);
GreaterThan and LessThan keywords for statistical comparisons allow us to select entities whose value of the attribute is greater or less than the specified value.
List<Book> findByPublishedYearGreaterThan(int year);
List<Book> findByPublishedYearLessThan(int year);
Used to find entities with a property value within a specified range.
List<Book> findByPublishedYearBetween(int startYear, int endYear);
To check for null or non-null properties:
List<Book> findByAuthorIsNull();
List<Book> findByAuthorIsNotNull();
For partial string matching, Like and Containing keywords are particularly useful.
List<Book> findByTitleLike(String titlePattern);
List<Book> findByTitleContaining(String titleFragment);
To find entities with string properties starting or ending with a specific substring.
List<Book> findByTitleStartingWith(String prefix);
List<Book> findByTitleEndingWith(String suffix);