13

I want the query not to return any values. I can't just not query database, so I'd like to add some unreachable condition to predicates, something like 'where 1 <> 1'. But the CriteriaBuilder.equal() doesn't allow to do that. Is there any way to reach the goal?

Thanks.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • try with the 1=0 for more detail see this post [http://stackoverflow.com/questions/6145809/mysql-where-1-0-confusion/6145827#6145827][1] [1]: http://stackoverflow.com/questions/6145809/mysql-where-1-0-confusion/6145827#6145827 – Pratik Aug 08 '11 at 11:00
  • 1
    @Pratik, the problem is how to write the condition in criteria api. The condition itself is not a problem. – Vladimir Ivanov Aug 08 '11 at 11:08

4 Answers4

16

How about

CriteriaBuilder.notEqual(CriteriaBuilder.literal(1), 1)

Although, if you know that this shouldn't execute, then using expressions might not be optimal on some RDBMS, if the database can't peek at bind values. I don't know how to do create a JPA Predicate with an inlined 1 <> 1 SQL expression, though...

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
8

Javadoc from CriteriaBuilder: "Create a disjunction (with zero disjuncts). A disjunction with zero disjuncts is false."

CriteriaBuilder cb..
Predicate itsFalse = cb.disjunction();

And then generated SQL depends about implementation, Hibernate produces 0=1. Why I prefer this method over other alternatives, is:

  1. According documentation it fits perfectly to this use without additional arguments and you kind of guess what it does from name.
  2. It is short.
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
7

How about this:

CriteriaBuilder.isTrue(CriteriaBuilder.literal(Boolean.FALSE));
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I don't think there are any other technologies, short of digging round in the implementation classes of a particular JPA implementation. – Stephen C Aug 08 '11 at 11:24
0
criteriaBuilder.isTrue(criteriaBuilder.literal(false));

or

Specification<TheEntity> specification = (root, query, cb) -> cb.isTrue(cb.literal(false));
volkov_kv
  • 21
  • 2
  • 1
    Could you add some explanation, why you think that these lines solve the issue? What is the difference between bove proposals? – Trinimon Mar 07 '23 at 20:37