Specification<User> spec1 = (root, query, cb) -> cb.equal(root.get("status"), "ACTIVE"); Specification<User> spec2 = (root, query, cb) -> cb.greaterThan(root.get("age"), 18); Specification<User> combined = spec1.and(spec2); List<User> results = userRepository.findAll(combined);
and() method combines conditions logically.The and() method combines two specifications so that both conditions must be true for a record to be included. Here, only users who are ACTIVE and older than 18 are returned.
Specification<Product> spec = (root, query, cb) -> cb.like(root.get("name"), "%phone%");
All options are identical and syntactically correct. This is a trick question to confirm understanding that the given code is valid.
Specification<Order> spec = (root, query, cb) -> cb.equal(root.get("nonExistentField"), "value"); List<Order> orders = orderRepository.findAll(spec);
Accessing a field that does not exist in the entity causes a runtime error because the query cannot be constructed properly.
Specification<User> spec = Specification.where(null); if (name != null) { spec = spec.and((root, query, cb) -> cb.like(root.get("name"), "%" + name + "%")); } if (email != null) { spec = spec.and((root, query, cb) -> cb.equal(root.get("email"), email)); } List<User> users = userRepository.findAll(spec);
Starting with Specification.where(null) means no filtering. If no conditions are added, the query returns all records.
The Specification pattern enables composing query conditions dynamically and reusing them, which is ideal for complex and flexible filtering.
