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お試し #3 新規登録

Last updated at Posted at 2024-12-30

Prev

概要

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

image.png

ソースコード

ユーザ新規登録

  • フォームに入力した情報をDBに登録しユーザ一覧取得を行った際に表示されるよう実装
  • IDは自動採番のため入力する項目は名前、年齢、住所の3項目とする

UserMapper.xml

UserMapper.xml
    <!-- 入力された情報を受け取りデータを登録 -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO users(
            username,
            age,
            address
        )
        VALUES(
            #{username},
            #{age},
            #{address}
        )
    </insert>
  • usernameageaddressを受け取りDBにINSERTする
  • useGeneratedKeyをtrueにすることで自動採番を有効化
  • 採番先はkeyPropertyで指定したフィールドになる

UserMapper.java

UserMapper.java
    /**
     * データを登録
     */
    void insert(UserEntity userEntity);

UserLogic.java

UserLogic.java
    /**
     * insertメソッドを呼び出し
     * データを登録
     */
    public void insert(UserDto userDto) throws DuplicateKeyException {

        UserEntity userEntity = toEntity(userDto);
        userMapper.insert(userEntity);
    }

    /**
     * UserDtoからUserEntityに変換
     */
    public UserEntity toEntity(UserDto userDto) {

        UserEntity userEntity = new UserEntity();
        userEntity.setId(userDto.getId());
        userEntity.setUsername(userDto.getUsername());
        userEntity.setAge(userDto.getAge());
        userEntity.setAddress(userDto.getAddress());
        return userEntity;
    }
  • insertメソッドでは入力情報として受け取ったuserDtouserEntityに変換しUserMapperインタフェースのinsertメソッドを呼び出す

MybatisController.java

MybatisController.java
    /**
     * ユーザ登録画面表示
     */
    @GetMapping("/userRegist")
    public String entry(Model model) {

        model.addAttribute("userDto", new UserDto());
        return "regist/userRegist";
    }

    /**
     * ユーザ登録完了画面表示
     */
    @PostMapping("/registComplete")
    public String regist(@ModelAttribute UserDto userDto) throws DuplicateKeyException {

        userLogic.insert(userDto);
        return "regist/registComplete";
    }
  • localhost:8080/userRegistにアクセスすると新規ユーザ登録用の画面に遷移
  • 入力する情報をuserDtoというオブジェクトとして持てるようentryメソッドのaddAttributeメソッド内でインスタンス化
  • 登録ボタンを押下すると、入力した情報がuserDtoとしてregistメソッドに渡される
    • 渡される際はPOSTメソッドで渡されるため、アノテーションは@PostMappingを使用
  • モデル層のinsertメソッドを呼び出し入力したデータをDBに保存
  • 保存後はlocalhost:8080/registCompleteにて登録完了のメッセージを表示

userRegist.html

  • 登録情報入力画面
userRegist.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>ユーザ新規登録</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>

<body>
    <div class="container mt-3">
        <h1>ユーザ新規登録</h1>
        <form th:action="@{/registComplete}" th:object="${userDto}" method="post">
            <div class="mb-3">
                <label for="userName" class="form-label">ユーザ名</label>
                <input type="text" class="form-control" id="userName" th:field="*{username}" required>
            </div>
            <div class="mb-3">
                <label for="userAge" class="form-label">年齢</label>
                <input type="text" class="form-control" id="userAge" th:field="*{age}" required>
            </div>
            <div class="mb-3">
                <label for="userAddress" class="form-label">住所</label>
                <input type="text" class="form-control" id="userAddress" th:field="*{address}" 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>
  • POSTメソッドを使用するため、formタグのmethod属性はPostを指定
  • th:actionではボタンを押した際の遷移先を指定
  • 今回はlocalhost:8080/registCompleteに遷移するためregistCompleteを指定

registComplete.html

  • 登録完了画面
registComplete.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>メイン画面</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>

<body>
    <div class="container mt-3">
        <h1>登録完了</h1>
        <p>ユーザの登録が完了しました。</p>

        <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>

ユーザ登録

  • IDが5のユーザを新規登録してみる

image.png

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?