Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you remove a criterion from criteria?

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

like image 389
ChuckM Avatar asked Mar 12 '10 15:03

ChuckM


3 Answers

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

like image 108
dpb Avatar answered Oct 22 '22 17:10

dpb


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.

like image 1
Pascal Thivent Avatar answered Oct 22 '22 18:10

Pascal Thivent


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();
            }
        }
    }
}
like image 1
otaviodecampos Avatar answered Oct 22 '22 18:10

otaviodecampos