3

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?

Jose Ospina
  • 2,097
  • 3
  • 26
  • 40
  • Start with a valid but impossible condition. – fzzfzzfzz May 30 '15 at 12:10
  • so the structure is ok, I just need to initialize or_exp as false. But how to do it correctly?. Can you give me an example of a valid but impossible condition? – Jose Ospina May 30 '15 at 12:21
  • That's why I commented instead of answering - I've only done this with raw SQL strings :) In raw SQL, you'd start with something like `1 != 1` and add `OR` statements to that. I don't know Hibernate criteria well enough to give the equivalent. – fzzfzzfzz May 30 '15 at 12:23

1 Answers1

2

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);
fzzfzzfzz
  • 1,248
  • 1
  • 12
  • 22