[英]Adding multiple arguments to criteria based on further conditions
I want to create a Hibernate query with criteria that dynamically changes based on further conditions 我想创建一个Hibernate查询,其标准根据其他条件动态更改
Example 例
First, create criteria.
首先,创建标准。
if (condition 1 applies) {add another argument to the criteria}
if(条件1适用){在条件中添加另一个参数}
if (condition 2 applies) {add another argument to the criteria} else {add another argument to the criteria}
if(条件2适用){在条件中添加另一个参数} else {在条件中添加另一个参数}
Finally, get the result in a list.
最后,将结果放入列表中。
I have this snippet so far. 到目前为止我有这个片段。
Unfortunately, I haven't got provided with a test environment so I cannot test what happens if I put another query.where
command after the first one. 不幸的是,我没有提供测试环境所以我无法测试如果我在第一个之后放入另一个
query.where
命令会发生什么。 I'd like to use multiple where
clauses, first always use one as a base, then add more if certain conditions met. 我想使用多个
where
子句,首先总是使用一个作为基础,然后在满足某些条件时添加更多。
session = HibernateUtil.openSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<MyClass> query = cb
.createQuery(MyClass.class);
Root<MyClass> root = query.from(MyClass.class);
query.select(root);
query.where(
cb.and(
cb.equal(root.get("dataPointId"), container.getDataPointId()),
cb.equal(root.get("datapointSubNumber"), subnumber)
)
);
I want to specifiy more where clauses based on conditions and get the result as a List<MyClass>
. 我想根据条件指定更多where子句,并将结果作为
List<MyClass>
。
You can use CriteriaBuilder
and pass an array of Predicates
to it. 您可以使用
CriteriaBuilder
并将Predicates
数组传递给它。 While adding the predicates you can have your if-else based on conditions to build a dynamic list. 添加谓词时,您可以根据条件构建动态列表。 You can have your complex logic and build predicates array accordingly.
您可以拥有复杂的逻辑并相应地构建谓词数组。
Something like this: 像这样的东西:
List<Predicate> predicates = new ArrayList<Predicate>();
if ( <some condition> ) {
predicates.add(criteriaBuilder.like(<your query condition>));
} else {
predicates.add(criteriaBuilder.equal(<your query condition>));
}
And at last: 最后:
query.where(criteriaBuilder.and(predicates.toArray()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.