springbootで簡単なCRUDを作る - ozaki25/springboot_app GitHub Wiki

前提

Entityの作成

  • src/main/java/com/example/sample/domain/User.javaを作成する
package com.example.sample.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

repositoryの作成

  • src/main/java/com/example/sample/domain/UserRepository.javaを作成する
package com.example.sample.domain;

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

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

serviceの作成

  • src/main/java/com/example/sample/service/UserService.javaを作成する
package com.example.sample.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.sample.domain.User;
import com.example.sample.domain.UserRepository;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public User findOne(Long id) {
        return userRepository.findOne(id);
    }

    public User save(User user) {
        return userRepository.save(user);
    }

    public void delete(Long id) {
        userRepository.delete(id);
    }
}

controllerの作成

  • src/main/java/com/example/sample/web/UserController.javaを作成する
package com.example.sample.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.sample.domain.User;
import com.example.sample.service.UserService;

@Controller
@RequestMapping("users")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("users", userService.findAll());
        return "users/index";
    }

    @RequestMapping(value = "new", method = RequestMethod.GET)
    public String newUser(Model model) {
        model.addAttribute("user", new User());
        return "users/new";
    }

    @RequestMapping(value = "{id}/edit", method = RequestMethod.GET)
    public String edit(@PathVariable Long id, Model model) {
        User user = userService.findOne(id);
        model.addAttribute("user", user);
        return "users/edit";
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public String show(@PathVariable Long id, Model model) {
        User user = userService.findOne(id);
        model.addAttribute("user", user);
        return "users/show";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String create(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public String update(@PathVariable Long id, @ModelAttribute User user) {
        user.setId(id);
        userService.save(user);
        return "redirect:/users";
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public String destroy(@PathVariable Long id) {
        userService.delete(id);
        return "redirect:/users";
    }
}

templateの作成

一覧画面

  • src/main/resources/templates/users/index.htmlを作成する
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>Listing Users</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h1>Listing User</h1>
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th></th>
            <th></th>
            <th></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>
            <td><a class="btn btn-default btn-xs" th:href="@{/users/{id}(id=${user.id})}">Show</a></td>
            <td><a class="btn btn-default btn-xs" th:href="@{/users/{id}/edit(id=${user.id})}">Edit</a></td>
            <td>
              <form th:action="@{/users/{id}(id=${user.id})}" th:method="delete">
                <input class="btn btn-default btn-xs" type="submit" value="destroy" />
              </form>
            </td>
          </tr>
        </tbody>
      </table>
      <a class="btn btn-default btn-xs" href="/users/new">New</a>
    </div>
  </body>
</html>

新規作成画面

  • src/main/resources/templates/users/new.htmlを作成する
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>New User</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h1>New User</h1>
      <form action="/users" th:method="post">
        <div class="form-group">
          <label class="control-laebl">Name</label>
          <input class="form-control" type="text" name="name" />
        </div>
        <div class="form-group">
          <label class="control-label">Age</label>
          <input class="form-control" type="text" name="age" />
        </div>
        <button class="btn btn-default btn-xs" type="submit">Create</button>
      </form>
      <div class="pull-right">
        <a class="btn btn-link btn-xs" href="/users">Back</a>
      </div>
    </div>
  </body>
</html>

編集画面

  • src/main/resources/templates/users/edit.htmlを作成する
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>Editing User</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h1>Editing User</h1>
      <form th:action="@{/users/{id}(id=${user.id})}" th:method="put">
        <div class="form-group">
          <label class="control-laebl">Name</label>
          <input class="form-control" type="text" name="name" th:value="${user.name}" />
        </div>
        <div class="form-group">
          <label class="control-label">Age</label>
          <input class="form-control" type="text" name="age" th:value="${user.age}" />
        </div>
        <button class="btn btn-default btn-xs" type="submit">Update</button>
      </form>
      <div class="pull-right">
        <a class="btn btn-link btn-xs" href="/users">Back</a>
      </div>
    </div>
  </body>
</html>

参照画面

  • src/main/resources/templates/users/show.htmlを作成する
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8" />
    <title>Show User</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
    <script src="/js/jquery.js"></script>
    <script src="/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h1>Show User</h1>
      <div>
        <label>ID</label>
        <p th:text="${user.id}"></p>
      </div>
      <div>
        <label>Name</label>
        <p th:text="${user.name}"></p>
      </div>
      <div>
        <label>Age</label>
        <p th:text="${user.age}"></p>
      </div>
      <div>
        <a class="btn btn-default btn-xs" th:href="@{/users/{id}/edit(id=${user.id})}">Edit</a>
      </div>
      <div class="pull-right">
        <a class="btn btn-link btn-xs" href="/users">Back</a>
      </div>
    </div>
  </body>
</html>

設定の追加

  • src/main/resources/application.propertiesに以下の内容を追記
spring.thymeleaf.cache: false
spring.jpa.hibernate.ddl-auto: update

css/jsの追加

jquery

  • 以下に配置(ファイル名が異なる場合はhtmlファイルを全て書き換えて下さい) src/main/resources/static/js/jquery.js

bootstrap

  • css/jsそれぞれ配置 src/main/resources/static/js/bootstrap.min.js src/main/resources/static/css/bootstrap.min.css

動作確認

一覧画面

2017-06-19 16 42 38

新規作成画面

2017-06-19 16 43 12

編集画面

2017-06-19 16 43 21

参照画面

2017-06-19 16 43 28
⚠️ **GitHub.com Fallback** ⚠️