For instance if I do something like:
Criteria c = session.createCriteria(Book.class)
.add(Expression.ge("release",reDate);
.add(Expression.ge("price",price);
.addOrder( Order.asc("date") )
.setFirstResult(0)
.setMaxResults(10);
c.list();
How can I use the same criteria instance, but remove (for example) the second criterion? I'm trying to build a dynamic query in which I'd like to let the user remove a filter, without the backend having to reconstruct the criteria from scratch.
Thank you
As far as I know, there is no way to remove things (restrictions, ordering, etc) from the criteria query, once you create it. I'm not knowledgeable enough about the internals of the Criteria API, but I know there is nothing in the exposed interface. You could try manipulating the objects that you are passing in to add
or addOrder
, but that sounds like more work than it is worth, especially when there are cleaner alternatives.
Criteria queries have certainly been one-shot uses in every application that I have seen.
Now, what you can do is store your restrictions, orderings and limits in a custom format (e.g., Collection
), and then build your query quite easily from that stored format. This would probably make more sense to your user interface since you certainly need fine-grained control from there.
Not the answer you are looking for, I'm sure, but it is exactly what I have done in the past.
HTH
How can I use the same criteria instance, but remove (for example) the second criterion? I'm trying to build a dynamic query in which I'd like to let the user remove a filter, without the backend having to reconstruct the criteria from scratch.
You can't, you'll have to resend the whole (updated) set of parameters used to build the dynamic query.
You can remove criterions in this way:
public static void List<CriterionType> removeCriterions(Criteria criteria, Class<? extends Criterion> type) {
Iterator<CriterionEntry> criterionIterator = ((CriteriaImpl) criteria).iterateExpressionEntries();
while (criterionIterator.hasNext()) {
CriterionEntry criterionEntry = criterionIterator.next();
if (criterionEntry.getCriteria() == criteria) {
Criterion criterion = criterionEntry.getCriterion();
if (null == type || criterion.getClass() == type) {
criterionIterator.remove();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With