Return Boolean Value from Spring Data JPA Query

Published on March 26, 2015 by

Did you know that you can return a boolean value from a Spring Data JPA query? For instance, you may want to know whether or not an entity (i.e. database row) exists with a given value for a field.¬†Surely one could simply return the row count and check if it is larger than zero, but it is a little more “clean” to return a boolean value. For this example, this can be accomplished¬†as in the code snippet below.

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

As you might have guessed, one can do like this for other use cases too, as long as we can use CASE WHEN (switch) and the query only returns a single row. This is usually the case when using aggregate functions such as COUNT, AVG, SUM, etc., unless they are used in combination with GROUP BY. If this is the case, then you would probably execute a native query anyways.

Featured

Learn Spring Framework today!

Take an online course and become a Spring Framework champion!

Here is what is covered:

  • The Spring Framework basics, including Spring MVC
  • How to work with JDBC and MySQL (in the context of Spring)
  • Build real applications step by step
  • A detailed walkthrough of Spring's core concepts
  • ... and much more!
Spring Framework logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

7 comments on »Return Boolean Value from Spring Data JPA Query«

  1. Benoit

    Thank you very much for the tip!

    • You are welcome – I’m happy that you found it useful! :-)

  2. OSA

    Thank you it was useful for me. I even haven’t known about CASE WHEN in mysql.

  3. Aksil

    good tip, thanks

  4. RK

    Great tip, exactly what I was looking for. Thank you!

  5. MS

    Cheers, good tip!

  6. Firza

    Unexpected token on when
    It gives me this error

Leave a Reply

Your e-mail address will not be published.