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?

More than 3 years have passed since last update.

SpringBoot + DB接続とCRUD操作【JPA】

Posted at

はじめに

書き留めてたけど勿体ないから投稿
※本業務が始まってしまったため
細かい説明とかは省略します~m(。-_-。)m

IntelliJ + Docker (APP+DB) + SpringBoot (Maven) 環境構築
で記事を記載したがこちらはjdbcTemplateを用いたJDBCの操作だった。今回はJPAを使用してCRUD操作を記載していく。
下準備は上記リンクの手順を行っていることを前提として話を進めていく。

画面

今回のゴール
screenshot.75.jpg

EntityとRepositoryクラスを作成

src\main\java\com\example\demo\Users
src\main\java\com\example\demo\UsersRepository

Users
package com.example.demo;

import lombok.Data;
import javax.persistence.*;

@Entity
@Table(name = "users")
@Data
public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private Integer money;
}

Lombokの@Dataを使用して
getter,setter,コンストラクタなどを自動作成しています

UsersRepository
package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}

JpaRepositoryを継承
CRUD操作に必要なメソッドであれば、これだけでOK

AppControllerを編集する

AppController
package com.example.demo.controller;

import com.example.demo.UserForm;
import com.example.demo.Users;
import com.example.demo.UsersRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class AppController {

    final
    UsersRepository usersRepository;
    final
    JdbcTemplate jdbcTemplate;

    public AppController(JdbcTemplate jdbcTemplate, UsersRepository usersRepository) {
        this.jdbcTemplate = jdbcTemplate;
        this.usersRepository = usersRepository;
    }

    @RequestMapping(path = "/")
    String index(Model model) {
        List<Users> users = usersRepository.findAll();
//        List<Map<String, Object>> users = jdbcTemplate.queryForList("select * from sample.users");
        model.addAttribute("users", users);

        return "index";
    }

    @RequestMapping(path = "/", method = RequestMethod.POST)
    String create(Model model, @ModelAttribute UserForm userForm) {
        Users user = new Users();
        user.setName(userForm.getName());
        user.setAge(userForm.getAge());
        usersRepository.save(user);

        List<Users> users = usersRepository.findAll();
        model.addAttribute("users", users);

        return "index";
    }

    @RequestMapping(path = "/update", method = RequestMethod.POST)
    String update(Model model, @ModelAttribute UserForm userForm) {
        Users user = new Users();
        user.setId(userForm.getId());
        user.setName(userForm.getName());
        user.setAge(userForm.getAge());
        usersRepository.save(user);

        List<Users> users = usersRepository.findAll();
        model.addAttribute("users", users);

        return "redirect:/";
    }

    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    String delete(Model model, @ModelAttribute UserForm userForm) {
        usersRepository.deleteById(userForm.getId());

        List<Users> users = usersRepository.findAll();
        model.addAttribute("users", users);

        return "redirect:/";
    }
}

JDBC(コメントアウトしてる部分)はSQL文をダイレクトに書いてDB接続
List<Map<String, Object>> users = jdbcTemplate.queryForList("select * from sample.users");

JPAはEntityとRepositoryクラスを介してDB接続
List<Users> users = usersRepository.findAll();
localhostにアクセスすれば同じようにユーザ一覧が表示される

index.html

index.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
            border-collapse: collapse;
        }

        th, td {
            padding: 3px 5px 3px 5px;
            border: 1px solid #aaa;
        }

        th {
            background-color: #eee;
        }
    </style>
</head>
<body>
<h1>ユーザ一覧</h1>
<table>
    <thead>
    <tr>
        <th>#</th>
        <th>name</th>
        <th>age</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="user: ${users}">
        <td th:text="${user['id']}"></td>
        <td th:text="${user['name']}"></td>
        <td th:text="${user['age']}"></td>
    </tr>
    </tbody>
</table>

<h1>ユーザー新規登録</h1>
<form action="/" name="create" method="post">
    <table>
        <tr>
            <th>名前</th>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <th>年齢</th>
            <td><input type="text" name="age"></td>
        </tr>
    </table>
    <div class="btn_area_center"><input type="submit" value="登録" class="btn"></div>
</form>

<h1>ユーザ編集</h1>
<form action="/update" name="update" method="post">
    <table>
        <tr>
            <th>ID</th>
            <td><input type="text" name="id"></td>
        </tr>
        <tr>
            <th>名前</th>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <th>年齢</th>
            <td><input type="text" name="age"></td>
        </tr>
    </table>
    <div class="btn_area_center"><input type="submit" value="登録" class="btn"></div>
</form>

<h1>ユーザ削除</h1>
<form action="/update" name="update" method="post">
    <table>
        <tr>
            <th>ID</th>
            <td><input type="text" name="id"></td>
        </tr>
    </table>
    <div class="btn_area_center"><input type="submit" value="登録" class="btn"></div>
</form>

</body>
</html>

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?