Sleep with dynamic constraints OR

I would like to add dynamic OR constraints to Hibernate's criterion based on the number of elements in an array.

In the example below, it Project

is an entity and a property of an @OneToMany

object User

. The object Project

has a property name

. db.getSes()

contains the current Session

.

My current approach

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 initialization or_exp = null

doesn't fit.

I'm not even sure if this is a way to implement a dynamic set of OR constraints on a sleeping request.

How should I do it?

+3


source to share


2 answers


Start with what is likely to be false.

You can use Restrictions.sqlRestriction to create a condition like this using raw SQL:



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

      

+2


source


I had the same problem ... hope this helps:



Hibernation disjunction

0


source







All Articles