Mybatis: how to check if a row exists and return a boolean?

Viewed 19362

The database is MySQL. The code should look like as below:

public interface UserMapper {
    @Select("....")
    boolean checkUserExists(@Param("email") String email);
}

Is it possible, and how to write the SELECT SQL? (can Exists be used?)

6 Answers

Para o mybatis reconhecer verdadeiro ou falsa, Este select deve retornar 0 ou 1, para isso usamos COALESCE. A consulta restorna o valor 1 e quando retorna null o coalesce retorna 0. Garanta que sua consulta retorno somente um registro.

For mybatis to recognize true or false, this select should return 0 or 1, for this we use COALESCE. The query returns the value 1 and when it returns null the coalesce returns 0. Make sure your query returns only one record.

public interface UserMapper {
    @Select("SELECT COALESCE ((SELECT 1 FROM TUser WHERE email=#{email}), 0) ")
    boolean checkUserExists(@Param("email") String email);
}

@Select("SELECT EXISTS(SELECT 1 FROM my_table WHERE email=#{email})") boolean checkUserExists(@Param("email") String email);

it is unnecessary to use FUNC "EXSITS(...)".

Usually, i like that.

@Select("select 1 from my_table where email = #{email} limit 1")
Optional<Boolean> checkUserExists(@Param("email") String email)
Related