5

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 =.

Depressio
  • 1,329
  • 2
  • 20
  • 39

2 Answers2

8

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 ...
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Bingo. I just debugged through my code that's creating the Predicates and found that it build a disjunction with nothing in it. Problem solved. Thanks! – Depressio Jun 06 '13 at 22:13
1

Similar to @JB Nizet answer, but to make it more concrete. In my case, I am using a CriteriaBuilder and the issue is that I am creating a list of predicates programmatically. In some cases, it generates an empty list of predicates and when I apply:

criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[] {})));

Appears the 0=1 issue. Simply checking if the predicates list is empty or not, and avoiding to adding to the where clause in the case it is empty, solves the issue.

King Midas
  • 1,442
  • 4
  • 29
  • 50