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

Viewed 1475

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

2 Answers

You need to select a boolean value.

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

Try following code:

@Repository
public interface UserRepository extends CrudRepository<UserEntity, Long> {

    Optional<UserEntity> findByName(final String name);
}

and then check whether user exists:

userRepository.findByName("username goes here")
                .orElseThrow(() -> new SecurityException("User not found in database"));

or:

userRepository.findByName("username goes here").isPresent()
Related