users@glassfish.java.net

Re: Dynamic JPA 2.0 query using Criteria API

From: <glassfish_at_javadesktop.org>
Date: Wed, 23 Jun 2010 07:35:01 PDT

Are you looking for an example? It wouldn't be difficult to modify the example given to use 'or' in the loop instead. Also note, that the example is incorrect - each subsequent loop calling cq.where will replace the previous where clause, so that only the last in the loop is used.

Or takes two predicates or an array of predicates. Assuming you have an array of Predicates:
        Predicate a = restrictions[0];
        for (int i = 1; i < max; ++i){
            a = criteriaBuilder.or(a, restrictions[i]);
        }
gives a, which is the same as:
    Predicate a = criteriaBuilder.or(restrictions);
You would then add them to the selection criteria via the where call outside the loop:
  cq.where(a);

So modifying the previous example could be something like

public void arbitraryParameterMethod(List<String> parameters) {
  // list to store query results
  List<Foo> results = new ArrayList<Foo>();
 
  //set up the Criteria query
  CriteriaBuilder cb = em.getCriteriaBuilder();
  CriteriaQuery<Foo> cq = cb.createQuery(Foo.class);
  Root<Foo> foo= cq.from(Foo.class);
 
  // loop through the list of parameters
  Iterator<String> i = parameters.iterator();
  Predicate a = null;
  if (i.hasNext())
    a = cb.equal(foo.get(Foo_.name), i.next());
  while (i.hasNext()) {
    String parameter = i.next();
    Predicate a = cb.or(cb.equal(foo.get(Foo_.name), parameter));
  }
  cq.where(a);
  // finish and execute the query
  cq.select(foo);
  TypedQuery<Foo> q = em.createQuery(cq);
  results = q.getResultList();
}
[Message sent by forum member 'chris_delahunt']

http://forums.java.net/jive/thread.jspa?messageID=475529