Bird
Raised Fist0
Spring Bootframework~20 mins

Specification pattern for dynamic queries in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Specification Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does Specification combine multiple conditions?
Given two Specification objects combined with and(), what is the resulting behavior when querying the database?
Spring Boot
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);
AReturns users who are either ACTIVE or older than 18.
BReturns users who are ACTIVE but ignores age condition.
CReturns users older than 18 but ignores status condition.
DReturns users who are ACTIVE and older than 18.
Attempts:
2 left
💡 Hint
Think about how the and() method combines conditions logically.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Specification
Which option contains a syntax error in the Specification lambda expression?
Spring Boot
Specification<Product> spec = (root, query, cb) -> cb.like(root.get("name"), "%phone%");
A;)"%enohp%" ,)"eman"(teg.toor(ekil.bc >- )bc ,yreuq ,toor( = ceps >tcudorP<noitacificepS
BSpecification<Product> spec = (root, query, cb) -> cb.like(root.get("name"), "%phone%");
CSpecification<Product> spec = (root, query, cb) -> cb.like(root.get("name"), "%phone%")
Dpecification<Product> spec = (root, query, cb) -> cb.like(root.get("name"), "%phone%");
Attempts:
2 left
💡 Hint
Check for missing or misplaced characters in the lambda expression.
🔧 Debug
advanced
2:00remaining
Why does this Specification cause a runtime error?
Consider this Specification code snippet. What causes the runtime error?
Spring Boot
Specification<Order> spec = (root, query, cb) -> cb.equal(root.get("nonExistentField"), "value");
List<Order> orders = orderRepository.findAll(spec);
AThe field 'nonExistentField' does not exist in the Order entity, causing a runtime exception.
BThe Specification lambda is missing a return statement.
CThe query parameter is null, causing a NullPointerException.
DThe CriteriaBuilder 'cb' is not initialized properly.
Attempts:
2 left
💡 Hint
Check if the field used in the query matches the entity's fields.
❓ state_output
advanced
2:00remaining
What is the result count of this dynamic Specification query?
Given this Specification that filters users by optional parameters, what is the count of users returned if both parameters are null?
Spring Boot
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);
AReturns users filtered by default criteria.
BThrows NullPointerException due to null Specification.
CReturns all users without filtering.
DReturns no users because Specification is null.
Attempts:
2 left
💡 Hint
Think about what happens when Specification.where(null) is used with no further conditions.
🧠 Conceptual
expert
2:00remaining
Why use Specification pattern for dynamic queries in Spring Data JPA?
Which is the best explanation for using the Specification pattern for dynamic queries?
AIt allows building complex queries by combining reusable predicates dynamically at runtime.
BIt automatically caches all queries to improve performance without extra code.
CIt replaces the need for any JPQL or SQL queries in the application.
DIt forces all queries to be static and predefined at compile time.
Attempts:
2 left
💡 Hint
Consider how dynamic conditions can be combined in a flexible way.

Practice

(1/5)
1. What is the main purpose of the Specification pattern in Spring Boot?
easy
A. To manage application configuration properties
B. To create REST API endpoints automatically
C. To handle HTTP request routing
D. To build flexible and reusable database queries dynamically

Solution

  1. Step 1: Understand the role of Specification pattern

    The Specification pattern is designed to help build database queries that can be combined and reused dynamically.
  2. Step 2: Compare with other options

    Options A, C, and D relate to other Spring Boot features like configuration, routing, and REST APIs, not query building.
  3. Final Answer:

    To build flexible and reusable database queries dynamically -> Option D
  4. Quick Check:

    Specification pattern = flexible queries [OK]
Hint: Specification pattern builds flexible queries step-by-step [OK]
Common Mistakes:
  • Confusing Specification with REST controller features
  • Thinking it manages app configuration
  • Assuming it handles HTTP routing
2. Which of the following is the correct method signature to implement in a Specification class in Spring Boot?
easy
A. public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder builder)
B. public void executeQuery(String sql)
C. public List<T> findAll()
D. public void configure()

Solution

  1. Step 1: Recall Specification interface method

    The Specification interface requires implementing the toPredicate method with parameters Root, CriteriaQuery, and CriteriaBuilder.
  2. Step 2: Eliminate incorrect options

    Options A, B, and C do not match the Specification interface method signature.
  3. Final Answer:

    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> Option A
  4. Quick Check:

    Specification method = toPredicate(...) [OK]
Hint: Specification requires toPredicate method with root, query, builder [OK]
Common Mistakes:
  • Using methods unrelated to Specification interface
  • Missing correct method parameters
  • Confusing with repository methods
3. Given the following Specification code snippet, what will be the result of the query?
Specification<User> spec = (root, query, builder) -> builder.equal(root.get("status"), "ACTIVE");
List<User> users = userRepository.findAll(spec);
medium
A. Throws a syntax error due to lambda usage
B. Returns all users regardless of status
C. Returns all users with status 'ACTIVE'
D. Returns users with status 'INACTIVE'

Solution

  1. Step 1: Analyze the Specification lambda

    The lambda creates a predicate that filters users where the 'status' field equals 'ACTIVE'.
  2. Step 2: Understand the repository call

    The findAll(spec) method applies this filter, returning only users matching the predicate.
  3. Final Answer:

    Returns all users with status 'ACTIVE' -> Option C
  4. Quick Check:

    Predicate filters status = ACTIVE [OK]
Hint: Predicate filters users by status 'ACTIVE' [OK]
Common Mistakes:
  • Assuming it returns all users without filtering
  • Thinking lambda causes syntax error
  • Confusing status values
4. Identify the error in this Specification implementation:
public class UserSpec implements Specification<User> {
public Predicate toPredicate(Root<User> root, CriteriaQuery query) {
return builder.equal(root.get("age"), 30);
}
}
medium
A. Missing CriteriaBuilder parameter in toPredicate method
B. Incorrect return type; should return boolean
C. Root parameter type is wrong
D. Method name should be buildPredicate

Solution

  1. Step 1: Check toPredicate method signature

    The Specification interface requires three parameters: Root, CriteriaQuery, and CriteriaBuilder.
  2. Step 2: Identify missing parameter

    The method is missing the CriteriaBuilder parameter, so it cannot build the predicate correctly.
  3. Final Answer:

    Missing CriteriaBuilder parameter in toPredicate method -> Option A
  4. Quick Check:

    toPredicate needs CriteriaBuilder parameter [OK]
Hint: toPredicate must have three parameters including CriteriaBuilder [OK]
Common Mistakes:
  • Omitting CriteriaBuilder parameter
  • Returning wrong type
  • Wrong method name
5. How can you combine two Specifications spec1 and spec2 to create a dynamic query that matches records satisfying both conditions?
hard
A. Use spec1.or(spec2)
B. Use Specification.where(spec1).and(spec2)
C. Use spec1.add(spec2)
D. Use spec1.merge(spec2)

Solution

  1. Step 1: Recall Specification combination methods

    Spring Data JPA Specification provides where(), and(), and or() methods to combine Specifications logically.
  2. Step 2: Combine for AND condition

    To match records satisfying both conditions, use Specification.where(spec1).and(spec2).
  3. Final Answer:

    Use Specification.where(spec1).and(spec2) -> Option B
  4. Quick Check:

    Combine specs with where().and() for AND logic [OK]
Hint: Use where().and() to combine Specifications with AND logic [OK]
Common Mistakes:
  • Using or() instead of and() for AND condition
  • Using non-existent add() or merge() methods
  • Not wrapping with Specification.where()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard