Bird
0
0

How can you implement a dynamic Specification that applies an OR condition between two Specifications specA and specB, but only if a certain flag is true; otherwise, it applies an AND condition?

hard📝 Application Q9 of 15
Spring Boot - Advanced Patterns
How can you implement a dynamic Specification that applies an OR condition between two Specifications specA and specB, but only if a certain flag is true; otherwise, it applies an AND condition?
ACreate a new Specification that manually builds predicates with CriteriaBuilder without using specA or specB
BUse <code>specA.and(specB)</code> always and ignore the flag
CUse <code>specA.or(specB)</code> always and ignore the flag
DUse <code>flag ? specA.or(specB) : specA.and(specB)</code> to combine the Specifications
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    We want to combine two Specifications with OR if flag is true, else with AND.
  2. Step 2: Use conditional logic

    Using the ternary operator, we can select between specA.or(specB) and specA.and(specB) based on the flag.
  3. Step 3: Implement dynamic combination

    This approach leverages Specification's built-in and() and or() methods for clean dynamic queries.
  4. Final Answer:

    Use flag ? specA.or(specB) : specA.and(specB) to combine the Specifications -> Option D
  5. Quick Check:

    Conditional combination with and/or [OK]
Quick Trick: Use ternary operator to switch between and/or [OK]
Common Mistakes:
  • Ignoring the flag and always using one operator
  • Manually building predicates unnecessarily
  • Not using Specification's and/or methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes