javahibernatehibernate-criteriaquery-by-example

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?


Solution

  • 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.