简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM