Skip to content

Instantly share code, notes, and snippets.

@muhdkhokhar
Created March 10, 2023 10:16
Show Gist options
  • Save muhdkhokhar/4d97d490fcb19df561a4c5066741f6ac to your computer and use it in GitHub Desktop.
Save muhdkhokhar/4d97d490fcb19df561a4c5066741f6ac to your computer and use it in GitHub Desktop.
public class PersonSpecifications {
public static Specification<Person> hasFirstName(String firstName) {
return (root, query, cb) -> cb.equal(root.get("firstName"), firstName);
}
public static Specification<Person> hasLastName(String lastName) {
return (root, query, cb) -> cb.equal(root.get("lastName"), lastName);
}
public static Specification<Person> hasAge(Integer age) {
return (root, query, cb) -> cb.equal(root.get("age"), age);
}
}
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> findAll(Specification<Person> spec);
}
Specification<Person> spec = PersonSpecifications.hasFirstName("John")
.and(PersonSpecifications.hasLastName("Doe"))
.and(PersonSpecifications.hasAge(30));
List<Person> results = personRepository.findAll(spec);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment