users@glassfish.java.net

Re: Dynamic JPA 2.0 query using Criteria API

From: <glassfish_at_javadesktop.org>
Date: Fri, 26 Mar 2010 12:55:13 PDT

Store the parameters in a List (or a Map) and iterate through them in a loop.

Something like:
[code]
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();
  while (i.hasNext()) {
    String parameter = i.next();
    cq.where(cb.equal(foo.get(Foo_.name), parameter));
  }
  // finish and execute the query
  cq.select(foo);
  TypedQuery<Foo> q = em.createQuery(cq);
  results = q.getResultList();
}
[/code]
[Message sent by forum member 'ievans']

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