title: Spring data JPA how to create a generic specification builder
body: <p>I have different specifications classes:</p>
  
  <pre><code>public class UserSpecification implements Specification&lt;ApplicationUser&gt; {
      private SearchCriteria criteria;
  
      public UserSpecification(SearchCriteria criteria) {
          this.criteria = criteria;
      }
  
      @SuppressWarnings("unchecked")
      @Override
      public Predicate toPredicate(Root&lt;ApplicationUser&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) {
         ...
      }
  }
  
  public class HotelSpecification implements Specification&lt;Hotel&gt; {
  
      private SearchCriteria criteria;
  
      public HotelSpecification(SearchCriteria criteria) {
          this.criteria = criteria;
      }
  
      @SuppressWarnings("unchecked")
      @Override
      public Predicate toPredicate(Root&lt;Hotel&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) {
        ...
      }
  }
  </code></pre>
  
  <p>So I try to use a generic builder to compose specifications of the same type because the builder class is 99% duplicate which only differs in class type.</p>
  
  <pre><code>public class MySpecificationBuilder {
      private final List&lt;SearchCriteria&gt; params;
  
      public MySpecificationBuilder () {
          params = new ArrayList&lt;&gt;();
      }
  
      public MySpecificationBuilder with(String key, String value) {
          params.add(new SearchCriteria(key, value));
          return this;
      }
  
      public Specification&lt;?&gt; build() {
          if (params.size() == 0) {
              return null;
          }
  
          List&lt;Specification&lt;?&gt;&gt; specs = new ArrayList&lt;&gt;();
          for (SearchCriteria param : params) {
              specs.add(new UserSpecification(param));  //how to make here generic
          }
  
          Specification&lt;?&gt; result = specs.get(0);
          for (int i = 1; i &lt; specs.size(); i++) {
              result = Specification.where(result).and(specs.get(i)); //warning 1
          }
          return result;
      }
  }
  </code></pre>
  
  <p>-warning 1: <a href="https://i.stack.imgur.com/2zXVX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2zXVX.png" alt="enter image description here"></a></p>
  
  <p>I would like to know if it encourages/it's possible to use a generic specification builder. If so, how do I create a generic builder for different specifications?</p>