title: How to initialize Specification of Spring Data JPA?
body: <p>I have a method that does a search with filters, so I'm using <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications" rel="noreferrer">Specification</a> to build a dynamic query:</p>
  
  <pre><code>public Page&lt;Foo&gt; searchFoo(@NotNull Foo probe, @NotNull Pageable pageable) {
  
          Specification&lt;Foo&gt; spec = Specification.where(null);  // is this ok?
  
          if(probe.getName() != null) {
              spec.and(FooSpecs.containsName(probe.getName()));
          }
          if(probe.getState() != null) {
              spec.and(FooSpecs.hasState(probe.getState()));
          }
          //and so on...
  
          return fooRepo.findAll(spec, pageable);
  }
  </code></pre>
  
  <p>There is the possibility that there are no filters specified, so I would list everything without filtering. So having that in mind, how I should initialize <code>spec</code> ? Right now, the code above doesn't work as it always returns me the same result: all the registers of the table, no filtering have been aplied althought <code>and</code> operations have been made. </p>
  
  <p>FooSpecs:</p>
  
  <pre><code>public class PrescriptionSpecs {
  
      public static Specification&lt;Prescription&gt; containsCode(String code) {
          return (root, criteriaQuery, criteriaBuilder) -&gt;
              criteriaBuilder.like(root.get(Prescription_.code), "%" + code + "%");
      }
  
      // some methods matching objects...
      public static Specification&lt;Prescription&gt; hasContractor(Contractor contractor) {
          return (root, criteriaQuery, criteriaBuilder) -&gt;
              criteriaBuilder.equal(root.get(Prescription_.contractor), contractor);
      }
      //... also some methods that access nested objects, not sure about this
      public static Specification&lt;Prescription&gt; containsUserCode(String userCode) {
          return (root, criteriaQuery, criteriaBuilder) -&gt;
              criteriaBuilder.like(root.get(Prescription_.user).get(User_.code), "%" + userCode + "%");
      }
  }
  </code></pre>