Search code examples
hibernatejpaentitymanager

Hibernate (or EntityManager?) adding "where 0=1" to query


I'm using the JPA EntityManager + Hiberate, and a myserious piece of the where clause is appearing. The debug from Hibernate is basically showing:

select /* bunch of columns */
from some_table
where /* several filters */
  and 0=1

This is happening when running javax.persistence.Query.getResultList. The Query has an array of Predicates in its where clause, but rest assured that 0 = 1 is not one of them.

I can find no possible reason why the 0=1 part is included in the query. Any ideas? I'd search for an answer first, but search engines ignore =.


Solution

  • This is how a disjunction is translated to SQL. See the javadoc for disjunction()

    Create a disjunction (with zero disjuncts). A disjunction with zero disjuncts is false.

    So, when an empty disjunction is created, it only contains the clause 1 = 0 (false). When additional predicates are added to the disjunction, they're simply added to the initial (false) one, separated with an or:

    where 1 = 0 or ...
    

    If you use a conjunction, it will be translated to

    where 1 = 1 and ...