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?

MyBatisお試し #4 データ削除

Last updated at Posted at 2025-01-13

Prev

概要

  • 業務でMyBatisを使用することがあったので理解度向上のために自宅でも色々触ってみる
  • 下記のような操作が可能なアプリを作成する

image.png

ソースコード

ユーザ削除

  • 指定したIDに対応するユーザ情報を削除できるよう実装
  • ユーザ検索と同様、指定したIDに対応するユーザが存在しない場合はエラー画面を表示

UserMapper.xml

UserMapper.xml
    <!-- 指定されたIDのユーザを削除 -->
    <delete id="delete" parameterType="int">
        DELETE FROM
            users
        WHERE
            id = #{id}
    </delete>
  • 指定したIDに対応するユーザのデータを削除
  • 引数としてIDが渡される

UserMapper.java

UserMapper.java
    /**
     * データを削除
     */
    int delete(int id) throws UserNotFoundException;
  • IDを引数として受け取りSQL文を実行する
  • ユーザが存在しない場合はUserNotFoundExceptionを投げる

UserLogic.java

UserLogic.java
    /**
     * deleteメソッドを呼び出し
     * データを削除
     */
    public void deleteUser(UserDto userDto) throws UserNotFoundException {

        findUser(userDto);
        userMapper.delete(userDto.getId());
    }
  • 最初にfindUserメソッドを呼び出すことにより指定したIDのユーザが存在するかどうかのチェックを実施
  • ユーザが存在しない場合はエラーを投げる
  • 存在する場合はdeleteメソッドを呼び出しユーザ情報の削除を実施

MybatisController.java

MybatisController.java
    /**
     * ユーザ削除画面表示
     */
    @GetMapping("/userDelete")
    public String delete() {

        return "delete/userDelete";
    }

    /**
     * ユーザ削除完了画面表示
     */
    @GetMapping("/deleteComplete")
    public String delete(@RequestParam("id") int id, Model model) {

        try {
            userDto.setId(id);
            userLogic.deleteUser(userDto);
        } catch (UserNotFoundException e) {
            model.addAttribute("errorMessage", e.getMessage());
            return "delete/deleteComplete";
        }
        model.addAttribute("deleteMessage", "削除が完了しました。");
        return "delete/deleteComplete";
    }
  • localhost:8080/userDeleteにアクセスすることで、削除したいユーザのIDを入力する画面へ遷移
  • 削除ボタンを押下すると入力したIDがGETメソッドによってlocalhost:8080/deleteCompleteに渡される
  • ユーザが存在する場合はdeleteUserメソッドにより削除を実行し、deleteMessageをビューへ返す
  • ユーザが存在しない場合はエラーメッセージをビューへ返す

userDelete.html

  • 削除するユーザのID入力画面
userDelete.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>ユーザ削除</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-3">
        <h1>ユーザ削除</h1>
        <form th:action="@{/deleteComplete}" method="get">
            <div class="mb-3">
                <label for="userId" class="form-label">ユーザID</label>
                <input type="number" class="form-control" id="userId" name="id" required>
            </div>
            <button type="submit" class="btn btn-primary">削除</button>
        </form>

        <a th:href="@{/main}" class="btn btn-secondary mt-3">メイン画面へ戻る</a>
    </div>
</body>

</html>
  • th:actionによって削除ボタンを押下した際の遷移先を指定
  • methodによってメソッドを指定
  • 今回は削除ボタンを押下するとGETメソッドにによってフォームに入力したIDをlocalhost:8080/deleteCompleteへ渡すよう実装

deleteComplete.html

  • 削除完了画面
deleteComplete.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>ユーザ一覧</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-3">
        <h1>削除結果</h1>
        <!-- 指定したIDのユーザが存在しない場合 -->
        <div th:if="${errorMessage}">
            <p th:text="${errorMessage}">指定したユーザは存在しません。</p>
        </div>
        <!-- 指定したIDのユーザが存在する場合 -->
        <div th:if="${deleteMessage}">
            <p th:text="${deleteMessage}">削除が完了しました。</p>
        </div>

        <a th:href="@{/allUsers}" class="btn btn-secondary mt-3">ユーザ一覧へ</a>
        <a th:href="@{/main}" class="btn btn-secondary mt-3">メイン画面へ戻る</a>
    </div>
</body>

</html>
  • ユーザ検索の際と同様、th:ifによりエラーメッセージが渡された場合と削除完了メッセージが渡された場合の条件分岐を実施

ユーザ削除

ユーザが存在する場合

  • IDが1のユーザを削除してみる

image.png

image.png

image.png

ユーザが存在しない場合

  • IDが5のユーザ(存在しない)を削除しようとする

image.png

image.png

Next

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?