Search code examples
spring-bootspring-data-jpaspring-elternary

Spring @Query with principal and ternary operator


@Query("select p from Person p where p.id=?#{principal=='anonymousUser'?0:principal.id})")
public Person getCurrentUser();

This method is intended to return a current user/person or nothing (there is no user with id=0 in the database) if the user is anonymous. And it works fine in the first case, but when the user is anonymous it gives an error:

org.hibernate.QueryException: Not all named parameters have been set: [1] [select p from Person p where p.id=?1)]

It seems it expects some parameters now, but why? Shouldn't the query be

select p from Person p where p.id=0

?


Solution

  • It seems it will work if you replaces 0 by null