[英]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. 我想根据数组中元素的数量动态地将OR限制添加到Hibernate标准中。
In the example below, Project
is an entity, and a @OneToMany
property of the User
entity. 在下面的示例中, Project
是一个实体,以及User
实体的@OneToMany
属性。 Project
entity has a property called name
. Project
实体有一个名为name
的属性。 db.getSes()
provides the current Session
. db.getSes()
提供当前的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. 但是or_exp = null
的初始化是不合适的。
I am not even sure if this is the way to implement a dynamic set of OR restrictions on a hibernate query. 我甚至不确定这是否是在hibernate查询上实现动态OR限制的方法。
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: 您可以使用Restrictions.sqlRestriction使用原始SQL构造此类条件:
Criterion impossibleCriterion = Restrictions.sqlRestriction("(1=0)");
LogicalExpression or_exp = Restrictions.or(impossibleCriterion, impossibleCriterion);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.