Search code examples
javaspring-bootspring-mvcspring-data-jpaspring-data

Spring Data/JPA - How can I check if a record already exists by name?


I have a question with Spring Data/JPA, I would like to know if there is any way to check if a name is already registered in the database with some function in the Repository with parameters.

I have the idea of ​​using a boolean, but I don't know how to execute it correctly to get the expected result.

@Query(nativeQuery= true, value="SELECT first_name FROM students WHERE first_name = :firstname")
boolean findByFirstname(String firstname);

Solution

  • Boolean return type for an EXISTS style query is not supported by JPA.

    However, you can work around this by creating a default method that has the signature you want and that calls the JPA method.

    default boolean existsByFirstname(String firstname) {
        return !findByFirstname(firstname).isEmpty();
    }
        
    @Query(nativeQuery= true, value="SELECT first_name FROM students WHERE first_name = :firstname")
    List<String> findByFirstname(String firstname);