Sergio Santiago
Sergio Santiago

Reputation: 1514

Hibernate org.hibernate.criterion.Example.create OR clause

I'm using org.hibernate.criterion.Example.create to create my query from my Entity object. Everything is fine, but using this method the SQL is only created with AND clause between the restrictions.

Is it possible to use org.hibernate.criterion.Example.create but with OR clause?

Upvotes: 2

Views: 2596

Answers (3)

TonyW
TonyW

Reputation: 18895

an old post from SO may be helpful: Hibernate Criteria Restrictions AND / OR combination

Criteria criteria = getSession().createCriteria(clazz); 
Criterion rest1= Restrictions.and(Restrictions.eq("A", "X"), 
           Restrictions.in("B", Arrays.asList("X","Y")));
Criterion rest2= Restrictions.and(Restrictions.eq("A", "Y"), 
           Restrictions.eq("B", "Z"));
criteria.add(Restrictions.or(rest1, rest2));

Upvotes: 1

Arturo Volpe
Arturo Volpe

Reputation: 3627

The short answer is no, you can not do it, but you can implement a OrExample, it's pretty easy, only check the source code of the Example and change the and for or (see sourcecode line 329). Since the methods are protected, you can extend it and override just the necesary.

Something like this:

public class OrExample extends org.hibernate.criterion.Example {

    @Override
    protected void appendPropertyCondition(
        String propertyName,
        Object propertyValue,
        Criteria criteria,
        CriteriaQuery cq,
        StringBuffer buf)
    throws HibernateException {
        Criterion crit;
        if ( propertyValue!=null ) {
            boolean isString = propertyValue instanceof String;
            if ( isLikeEnabled && isString ) {
                crit = new LikeExpression(
                        propertyName,
                        ( String ) propertyValue,
                        matchMode,
                        escapeCharacter,
                        isIgnoreCaseEnabled
                );
            }
            else {
                crit = new SimpleExpression( propertyName, propertyValue, "=", isIgnoreCaseEnabled && isString );
            }
        }
        else {
            crit = new NullExpression(propertyName);
        }
        String critCondition = crit.toSqlString(criteria, cq);
        if ( buf.length()>1 && critCondition.trim().length()>0 ) buf.append(" or ");
        buf.append(critCondition);
    }

See the or instead of the original and.

Upvotes: 1

JamesB
JamesB

Reputation: 7894

Yes, you can

session.createCriteria(Person.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", "James")) .add(Restrictions.eq("age", 20)) );

In the example above, class Person would have properties name and age and you would be selecting those people with name = "James" or age = 20.

Upvotes: 1

Related Questions