✅ Common Spring Data JPA Query Keywords
| Keyword | Meaning | Example Method |
|---|---|---|
And, Or | Logical conjunction/disjunction | findByFirstNameAndLastName |
Is, Equals | Exact match | findByEmailIs(String email) |
Not | Negation | findByFirstNameNot(String name) |
In, NotIn | Collection match | findByIdIn(List<String> ids) |
Like | SQL LIKE, % must be added manually | findByEmailLike(String pattern) |
Contains | LIKE %x% | findByEmailContaining(String part) |
StartsWith | LIKE x% | findByEmailStartingWith(String prefix) |
EndsWith | LIKE %x | findByEmailEndingWith(String suffix) |
IgnoreCase | Case-insensitive match | findByFirstNameIgnoreCase(String name) |
GreaterThan | > comparison | findByAgeGreaterThan(int age) |
LessThan | < comparison | findByAgeLessThan(int age) |
Between | Range | findByCreatedAtBetween(start, end) |
Before, After | Date/time comparisons | findByUpdatedAtAfter(LocalDateTime dt) |
IsNull, NotNull | Check for null values | findByPhoneNumberIsNull() |
True, False | Boolean flags | findByActiveTrue() |
🧰 Dynamic Queries: Spring Data Specifications
For dynamic filtering (e.g. search by optional fields), use JPA Specifications.
✅ Step 1: Extend JpaSpecificationExecutor
public interface UserRepository extends
BaseRepository<User, String>,
JpaSpecificationExecutor<User> {
}✅ Step 2: Create a Specification<User>
public class UserSpecifications {
public static Specification<User> hasFirstName(String name) {
return (root, query, cb) ->
cb.equal(root.get("firstName"), name);
}
public static Specification<User> emailContains(String fragment) {
return (root, query, cb) ->
cb.like(cb.lower(root.get("email")), "%" + fragment.toLowerCase() + "%");
}
}✅ Step 3: Use It Dynamically
Specification<User> spec = Specification.where(null);
if (firstName != null) {
spec = spec.and(UserSpecifications.hasFirstName(firstName));
}
if (emailFragment != null) {
spec = spec.and(UserSpecifications.emailContains(emailFragment));
}
List<User> users = userRepository.findAll(spec);🚀 When to Use
| Use Case | Approach |
|---|---|
| Simple lookups | Method naming |
| Optional/multiple filters | Specifications |
| Complex joins, subqueries | @Query or Criteria |
Let me know if you want:
-
A ready-to-use dynamic
UserSearchRequest+ filter logic -
Integration of Specifications in your service layer
-
Paginated dynamic filtering with sorting