I'm trying to run a query that checks if some conditions are true and returns a simple boolean result as output. What makes it slightly tricky is that one of the conditions is to test for whether no results are returned for a set of criteria.
I'm currently using JPA-2.0 with hibernate as my provider, backed by MySQL. I have gotten an example query working fine in MySQL, but when trying to get it running in JPQL it flops. The MySQL query looks a bit like this:
Select exists(Select statement with criteria)
or not exists(Select statement with criteria);
I also got the same output using CASE, but as JPQL doesn't support that statement.
Anyways, when I try to use a similar query in JPQL I get the error:
"unexpected end of subtree"
which from my understanding means that something is missing in the query. Does anyone have any idea how to fix it?
You can do a boolean query using a case expression.
As of JPA 2.0 (Java EE 6) you can create a TypedQuery .
String query = "select case when (count(*) > 0) then true else false end from ......"
TypedQuery<Boolean> booleanQuery = entityManager.createQuery(query, Boolean.class);
boolean exists = booleanQuery.getSingleResult();
In JPA 1.0 (Java EE 5) you must use an untyped query.
Query booleanQuery = entityManager.createQuery(query);
boolean exists = (Boolean) booleanQuery.getSingleResult();