Search code examples
javahibernatecriteriahibernate-criteria

hibernate total criterions in a junction


I fill a junction based on conditions coming from a filter:

if (filter.getName() != null) conjunction.add(...);
if (filter.getSurname() != null) conjunction.add(...);

At the end add the junction to my Criteria:

criteria.add(conjunction);

I would like to apply certain aliases to my criteria object only if the total number of criterions in the conjunction are > 0 (to optimize the query):

if (moreThanOneCriterion(conjunction)) {
    criteria.createCriteria("users", "user");
    criteria.add(conjunction); 
}

How can I know the total number of criterions in a junction ?

As an option, could add a counter variable inside each if block, but looking for a better/cleaner option.


Solution

  • Afaik (and according to docs) there's no method to get the number of criterions from a conjunction.

    Probably could do something like that

    boolean moreThanOneCriterion= false;
    if (filter.getName() != null) { conjunction.add(...); moreThanOneCriterion=true; }
    if (filter.getSurname() != null) { conjunction.add(...); moreThanOneCriterion=true; }
    

    and add the alias if moreThanOneCriterion is true (since it seems you're not really interested in the exact count of criterions)