Grails Create Criteria | Grails CreateCriteria | Custom Criteria | Custom Criteria Condition
You have to create a groovy class as below:
import org.hibernate.Criteria import org.hibernate.HibernateException import org.hibernate.criterion.CriteriaQuery import org.hibernate.criterion.Criterion import org.hibernate.engine.spi.TypedValue import org.hibernate.internal.util.StringHelper /** * Created by pritom on 25/09/2017. */ class CustomCriteria implements Criterion { private static final TypedValue[] NO_VALUES = new TypedValue[0] private final String propertyName CustomCriteria(String propertyName) { this.propertyName = propertyName } public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { String[] columns = criteriaQuery.findColumns(this.propertyName, criteria) String result = StringHelper.join(" or ", StringHelper.suffix(columns, " is not null")) if(columns.length > 1) { result = '(' + result + ')' } return result } public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return NO_VALUES } public String toString() { return this.propertyName + " is not null" } }
Then you to attach those functions as below:
Object.metaClass.with { customCriteria = { String propertyName = delegate.delegate.calculatePropertyName(it) delegate.delegate.addToCriteria(new CustomCriteria(propertyName)) return delegate.delegate } }
Then you can use your custom criteria function as below:
return (List<Home>) Home.createCriteria().list { setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) createAlias("childs", "childs") isNotNull("childs.id") customCriteria("childs.id") not { isNull("childs.id") } }