Barbra Barbra - 6 days ago 5
Java Question

'case when exists' @Query with Hibernate

I have a @Repository interface with a following method for checking IF database contains a record colliding (in business domain meaning) with the one I'm about to persist (I don't care about WHAT the colliding records are):

@Query("select case when exists (
select me from MyEntity me where {my conditions regarding someParam here}
) then true else false end from MyEntity")
boolean findColliding(@Param("someParam") String someParam);


The table on which I run it is empty (PostgreSQL) therefore the exists subquery shouldn't find anything and I believe the whole method should return false as case states it can only return true if exists and false otherwise.

It returns null #facepalm

My query passes query syntax check on startup (no QuerySyntaxException) but throws exception when executed:

Null return value from advice does not match primitive return type for: public abstract boolean findColliding(...)


What am I doing wrong? Should I take some other approach for my problem?

Hibernate 5.0.11.Final

Answer

JPA 2.1 CASE expression only supports scalar expressions, not queries.

For more details, check out the JPA specification.

You need to use a native SQL query instead.

Comments