I have a test case (will add shortly) If you test for entity type via type() inside a selectCase() expression, Hibernate generates incorrect SQL for the query. My test case looks like this:
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Integer> query = cb.createQuery(Integer.class);
final Root<Animal> animal = query.from(Animal.class);
final Expression<Boolean> isDog = JPAUtil.instanceOf(entityManager, animal, Dog.class);
final Expression<Integer> numSpots = cb.<Integer>selectCase()
.when(isDog, cb.treat(animal, Dog.class).get(Dog_.numSpots))
.otherwise(cb.literal(0));
query.select(numSpots);
Note that there is no WHERE clause in the query. Here is the SQL that Hibernate generates:
select
case
when a1_0.type in(?) then a1_0.numSpots
else 0
end
from
(select
*
from
Animal t
where
t.type='D') a1_0
Note that the SQL query contains where t.type='D' - this clause should not be there. We want to query over all animals, not just dogs. The above behavior is from Hibernate 6.1.7. In 5.6.15, you get this exception instead:
|