hibernatehibernate-criteriarestrictionrestrictions

Hibernate criteria with dynamic OR restrictions


I would like to add OR restricions dynamically to a Hibernate criteria based on the number of elements on an array.

In the example below, Project is an entity, and a @OneToMany property of the User entity. Project entity has a property called name. db.getSes() provides the current Session.

My current approach is

String[] project_name_filters = {"Project Name 1","Project Name 2"};

Criteria q = db.getSes().createCriteria(User.class);

if(project_name_filters.length > 0) {
    q.createAlias("project", "project");

    LogicalExpression or_exp = null;

    for(int ix_prj = 0 ; ix_prj < project_name_filters.length ; ix_prj++) {
            or_exp = Restrictions.or (or_exp,Restrictions.eq("project.name", project_name_filters[ix_prj]));
        }   

    q.add(or_exp);
}

@SuppressWarnings("unchecked")
List<User> users = (List<User>) q.list(); 

but the initialization of or_exp = null is not appropriate.

I am not even sure if this is the way to implement a dynamic set of OR restrictions on a hibernate query.

How should I do it?


Solution

  • Start with something that is certain to be false.

    You can use Restrictions.sqlRestriction to construct such a condition using raw SQL:

    Criterion impossibleCriterion = Restrictions.sqlRestriction("(1=0)");
    LogicalExpression or_exp = Restrictions.or(impossibleCriterion, impossibleCriterion);