Search code examples
javaspringjpaspring-data-jpa

JPA - check if the user exists in the database by name?


i'm triying user this code

public interface UserRepository extends CrudRepository<Usuario, Long> {

    @Query("select p from User p where name = ?1")
    public boolean findExistByname(String name);
    
    @Query("select p from User p where email = ?1")
    public boolean findExistByEmail(String email);
}

to check if the user in the database exists, but when not, it returns null and an error, I just don't know how to do this


Solution

  • You need to select a boolean value.

    @Query("select count(p) = 1 from User p where name = ?1")
    public boolean findExistByname(String name);