Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @Query with 'case when exists' does not work with Hibernate

I have a @Repository interface with the 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:

org.springframework.aop.AopInvocationException: 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

like image 845
Barbra Avatar asked Nov 27 '16 20:11

Barbra


People also ask

Can Spring data JPA work without Hibernate?

Spring Data JPA is really a set of dependencies that makes it easier to work with a JPA provider. Hibernate is one of several JPA providers. This means you can use Spring Data JPA without using Hibernate (if you really wanted to).

Can we use JPA with Hibernate?

Hibernate is an implementation of JPA. Hence, the common standard which is given by JPA is followed by Hibernate. It is a standard API that permits to perform database operations. It is used in mapping Java data types with SQL data types and database tables.

What is @query annotation in Hibernate?

If you want to use named query in hibernate, you need to have knowledge of @NamedQueries and @NamedQuery annotations. @NameQueries annotation is used to define the multiple named queries.


1 Answers

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

For more details, check out the JPA specification.

If the DB supports this syntax, you need to use a native SQL query instead.

like image 132
Vlad Mihalcea Avatar answered Nov 09 '22 22:11

Vlad Mihalcea