0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【重複してたらエラーにする方法】

0
Posted at

ユーザーを登録した際に、メールアドレスが重複してないかチェックして
重複してたらエラーが出るようにする設定方法。

Serviceクラス
if (usersRepository.existsByMailadress(mailadress)) {//existsByIdでそのidが存在してるかチェックできる
            throw new IllegalStateException("このアドレスは既に登録されています。頑張ってパスワードを思い出すか諦めてください。");
        }

if(すでに同じのがあるかチェックする処理){同じのがあった場合の処理}
という感じで考えた。
usersRepository.existsByMailadress(mailadress) 同じユーザがいるか探す処理existsBy〇〇 は値が存在するかチェックするJapメソッド。
だから、データベース内に同じメールアドレスが存在してるかチェックできる。
throw new IllegalStateExceptionはエラーを出すExceptionクラスのメソッド

Repositoryクラス
public interface UsersRepository  extends JpaRepository<Users, Integer> {
    boolean existsByMailadress(String mailadress);
}

Repositoryクラスにboolean existsByMailadress(String mailadress); を追加する。boolean は真 (true) と偽 (false) の2つの値しか取ることができない型。
existsBy〇〇 の引数はboolean型じゃないといけないからここでString mailadressからboolean型にしてる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?