Reputation: 444
I want to create a Hibernate query with criteria that dynamically changes based on further conditions
Example
First, create criteria.
if (condition 1 applies) {add another argument to the criteria}
if (condition 2 applies) {add another argument to the criteria} else {add another argument to the criteria}
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. I'd like to use multiple where
clauses, first always use one as a base, then add more if certain conditions met.
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>
.
Upvotes: 1
Views: 1648
Reputation: 81
You can use CriteriaBuilder
and pass an array of Predicates
to it. 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()));
Upvotes: 3