How to convert a Spring JPA Query Result to boolean

I’m always forgetting how to convert a Query Result to boolean… so here is a short reminder for that 😉 If you want to query and convert the result to boolean, then you have to either convert to true or false as a result:

@Repository
public interface ExampleRepository extends JpaRepository<Example, Integer> {
    @Query("SELECT CASE WHEN COUNT(e) > 0 THEN true ELSE false END FROM Example e WHERE e.name = :name")
    boolean existsByName(@Param("name") String companyName);
}

Thats the way if you want to see, if something exists, but what if you want to check for a specific value?

// Oracle SQL
@Repository
public interface ExampleRepository extends JpaRepository<Example, Integer> {
    @Query("SELECT CASE WHEN e.statusId = 5 THEN true ELSE false END FROM Example e WHERE e.id = :id")
    boolean isStatusValid(@Param("id") String id);
}

The only important thing for conversion to boolean is that only 1 row is returned and there is a valid value which java can convert.

Related Articles

Leave a Reply

Previous post That acid poison burns – Legend of Keepers
Tainted Grail: Conquest Next post Golems for the win! – Tainted Grail: Conquest