Search code examples
hibernate-criteria

Nested 'or' restriction in 'and' one leading in unexpected result


i am quite confused about how the Criteria API does build the final query. Here's some code :

someCriteria.add(
    Restrictions.and(
        Restrictions.or(Restrictions.gt(a,b),Restrictions.isNull(a)),
        Restrictions.ge(d,e)
    )

I was expecting something like

SELECT.. FROM... 
WHERE (A > B or A IS NULL) AND (D > E) 

But when I inspect my criteria entries, I see instead something like :

SELECT.. FROM... 
WHERE A > B or A IS NULL AND D > E

thus leading in unexpected result.

I am quite sure I could rewrite the query so that it is no more a problem, but since the application I am about to develop for is based on such queries, I need to understand the problem.

So, anyone could explain why I dot not get expected parentheses around the part of the query generated by the "Restrictions.or(...)"?

Thanks in advance.

PS : Hibernate core 4.3.4.Final


Solution

  • So the problem was not with "Criteria", but with my excessive trust in the debugging tools : the Criteria does actually match the first solution, ie adds parentheses around each generated restriction. But when I tried to log or watch the criterion entries inside the Criteria object, some parentheses were just not displayed, leading me into misinterpreting my problem.

    So the solution to understand the problem was to log the actual request (eg using property "show_sql" in the sessionFactoryBean and setting log4j.logger.org.hibernate.sql to TRACE level).