Search code examples
javasqlhibernateliferaycriteria

Using Criterion 'OR' to narrow resultset


I'm having trouble understanding how to implement the following query using Criterion:

SELECT * FROM FooTable WHERE bar = '1' OR bar = '2;

This is what I have currently:

public List<FooItem> getFooItems(List<Long> bars) throws SystemException {

    DynamicQuery query = DynamicQueryFactoryUtil.forClass(FooItem.class, PortletClassLoaderUtil.getClassLoader());

    if (Validator.isNotNull(bars)) {

        List<Criterion> barCriteria = new ArrayList<Criterion>();

        for (long bar: bars) {
            query.add((RestrictionsFactoryUtil.eq("bar", bar)));
        }

        if (!barCriteria.isEmpty()) {
            for (Criterion criteria : barCriteria) {
                query.add(criteria);
            }
        }
    }

    List<FooItem> result = FooItemLocalServiceUtil.dynamicQuery(query);

    return result;
}

However, my query looks like the following at runtime:

SELECT * FROM FooTable WHERE bar = '1' AND bar  = '2';

How can I turn these AND's into OR's statement?

Note: bar is not the primary key on the table.


Solution

  • You should use Restrictions.disjuntion(), try something like this

    if (!barCriteria.isEmpty()) {
        Disjunction or = Restrictions.disjunction();
        for (Criterion criteria : barCriteria) {
            or.add(criteria);
        }
        query.add(or);
    }