开发者

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开发者_如何学Python 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();
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜