Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 200
Igor Vinicius Avatar asked Sep 06 '25 03:09

Igor Vinicius


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);
like image 99
Akif Hadziabdic Avatar answered Sep 07 '25 16:09

Akif Hadziabdic


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()
like image 34
Lukasz Blasiak Avatar answered Sep 07 '25 16:09

Lukasz Blasiak