Search code examples
spring-data-jpajpa-criteria

Difference Between toPredicate() Method and And/Or/Not/Where in JPA Criteria API Specification<>


I am now exploring the JPA Criteria API for creating the dynamic queries and type safe queries. I am exploring how to use Specification. When I am exploring I found that toPredicate() method using to create where clause for the query referenced by the entity. Also exploring about And/Or/Not and where in Specification.

Actually if toPredicate() mMethod creating the where clause, then why we using the method "Where"? what is the role of other method when comparing toPredicate() method?


Solution

  • If you implement a Specification from scratch you implement toPredicate.

    If you already have one or more Specifications you can use and, or, and not to combine them into a new specification.

    For example, given two specifications isVip and placedAnOrderLastMonth you can combine them as such:

    shouldReceiveNagMail = isVip.and(not(placedAnOrderLastMonth));
    

    The where method is just syntactic sugar that people might like to use to make the code more readable. It just returns essentially the same Specification;