How to generate a predicate array of OR statements
criteria-api, jpa
Solution
The expression `CriteriaQuery<T> where(Predicate... restrictions)`, as you can see in the javadoc,
Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.
So, it makes the conjunction of the predicates in the list, i.e. it concatenates them with `AND` expressions. In order to concatenate them with `OR` expression, simply use `CriteriaBuilder#or(Predicate... restrictions)`
query.where(builder.or(predicates.toArray(new Predicate[] {})));
Problem
I am trying to use the Criteria API instead of constructing queries as JPQL Strings as the Criteria API seems much better suited for this. However, I am having a few problems understanding how to construct the two following statements. ``` SELECT e FROM Subject e WHERE e.company = :c1 OR e.company = :c2 OR e.company = :c3 ``` In this case I need to iterate over an unknown number of values (c1, c2, c3 etc.) to match to the same attribute. ``` SELECT e FROM Subject e WHERE e.company LIKE :c1 OR e.account LIKE :c1 OR e.email LIKE :c1 ``` In this case I need to pass in a single value (c1) and have a 'LIKE' comparison done on a specific range of attributes. My current pattern looks something like this: ``` // Criteria CriteriaBuilder builder = subjectDAO.criteriaBuilder(); CriteriaQuery<Subject> query = builder.createQuery(Subject.class); // Root Root<Subject> subject = query.from(Subject.class); List<Predicate> predicates = new ArrayList(); for (String property : map.keySet()) { String value = (String) coreFilter.get(map); predicates.add(????? This is where I come unstuck ?????); } // pass all the predicates into the query query.where(predicates.toArray(new Predicate[predicates.size()])); ``` NB. I don't have any problems constructing the Query object or specifying the Root or Joins. I am just having problems with the specificity of the above queries. For the sake of clarity just assume that all the attributes are String and don't require any joins.