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.
Method Signatures
The findBy method follows the pattern: findBy + PropertyName [+ Condition] [+ OrderBy]. Spring interprets the method name and executes the query.
Example:
Suppose we want to fetch books by an author published after a specific year, sorted by title.
Step 1: Entity Class
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String author;
private int publishedYear;
// constructors, getters, setters
}
Step 2: Repository Interface
Next, we will define the complex query in our repository interface.
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByAuthorAndPublishedYearGreaterThanOrderByTitleAsc(String author, int year);
}
- Finds books by a specific author with publishedYear > year.
- Results are sorted by title in ascending order.
Step 3: Service Layer
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> findBooksByAuthorPublishedAfterYear(String author, int year) {
return bookRepository.findByAuthorAndPublishedYearGreaterThanOrderByTitleAsc(author, year);
}
}
Using Condition Keywords in findBy Methods
Spring Data JPA supports various keywords to create complex queries directly from method names.
1. And
Combine multiple conditions
List<Book> findByAuthorAndPublishedYear(String author, int year);
2. Or
Match any one of multiple conditions
List<Book> findByAuthorOrTitle(String author, String title);
3. Combining And & Or
Suitable for complex Queries
List<Book> findByAuthorAndPublishedYearOrTitle(String author, int year, String title);
4. GreaterThan / LessThan
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);
5. Between
Used to find entities with a property value within a specified range.
List<Book> findByPublishedYearBetween(int startYear, int endYear);
6. IsNull / IsNotNull
To check for null or non-null properties:
List<Book> findByAuthorIsNull();
List<Book> findByAuthorIsNotNull();
7. Like / Containing
For partial string matching, Like and Containing keywords are particularly useful.
List<Book> findByTitleLike(String titlePattern);
List<Book> findByTitleContaining(String titleFragment);
8. StartingWith / EndingWith
To find entities with string properties starting or ending with a specific substring.
List<Book> findByTitleStartingWith(String prefix);
List<Book> findByTitleEndingWith(String suffix);