[JAVA] Erstellen Sie eine CRUD-App mit Spring Boot 2 + Thymeleaf + MyBatis

Entwicklungsumgebung

Aufbau einer Entwicklungsumgebung

Ein Projekt erstellen

image.png

--Wählen Sie Java 11. (Vielleicht ist Java 8 in Ordnung)

image.png

--Überprüfen Sie DevTools, Web, Thymeleaf, H2, MyBatis.

image.png

--Geben Sie den Projektnamen ein und Sie sind fertig.

image.png

Hot Deploy-Einstellungen 1/2

image.png

Hot Deploy-Einstellungen 2/2

--Geben Sie "Strg + Umschalt + a" → "Registrierung" ein und klicken Sie auf "Registrierung ...". (Wenn Intellij nicht ins Japanische übersetzt ist, geben Sie "Registrierung" ein und klicken Sie auf "Registrierung ...".)

image.png

--compiler. ... .running Check ☑.

image.png

Ändern Sie pom.xml

pom.xml


    <dependency>
      <groupId>nz.net.ultraq.thymeleaf</groupId>
      <artifactId>thymeleaf-layout-dialect</artifactId>
      <version>2.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>1.11.1</version>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>3.3.7-1</version>
    </dependency>

Erstellen Sie schema.sql, data.sql

schema.sql


CREATE TABLE IF NOT EXISTS user (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name varchar (50) NOT NULL
);

data.sql


INSERT INTO user (name) VALUES ('tanaka');
INSERT INTO user (name) VALUES ('suzuki');
INSERT INTO user (name) VALUES ('sato');

Entitätserstellung

--Erstellen Sie ein Entitätspaket und erstellen Sie eine Benutzerklasse darunter. --Erstellen Sie eine Klasse für Benutzerdaten. Für die Verwendung von MyBatis sind keine Anmerkungen erforderlich.

java:com.example.demo.entity.User.java


package com.example.demo.entity;


import org.hibernate.validator.constraints.NotBlank;

public class User {

  private int id;

  @NotBlank(message = "{require_check}")
  private String name;

  public int getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

}

Erstellen Sie mapper.java, mapper.xml

--Erstellen Sie ein Mapper-Paket und erstellen Sie eine UserMapper-Oberfläche darunter.

java:src/main/java/com.example.demo.mapper.UserMapper.java


package com.example.demo.mapper;

import com.example.demo.entity.User;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {

  List<User> selectAll();

  User select(int id);

  int insert(User user);

  int update(User user);

  int delete(int id);
}

src/main/resouces/com/example/demo/mapper/UserMapper


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
    <select id="selectAll" resultType="com.example.demo.entity.User">
        select * from user
    </select>
    <select id="select" resultType="com.example.demo.entity.User">
        select * from user where id = #{id}
    </select>
    <insert id="insert">
        insert into user (name) values (#{name})
    </insert>
    <update id="update">
        update user set name = #{name} where id = #{id}
    </update>
    <delete id="delete">
        delete from user where id = #{id}
    </delete>
</mapper>

Controller erstellen

HTTP-Methode URL Controller-Methode Erläuterung
GET /users getUsers() Anzeige des Listenbildschirms
GET /users/1 getUser() Bildschirm mit Details anzeigen
GET /users/new getUserNew() Anzeige des neuen Erstellungsbildschirms
POST /users postUserCreate() Fügen Sie die Verarbeitung des neuen Erstellungsbildschirms ein
GET /users/1/edit getUserEdit() Anzeige des Bearbeitungsbildschirms
PUT /users/1 putUserEdit() Bildschirmaktualisierungsprozess bearbeiten
DELETE /users/1 deleteUser() Prozess löschen

java:com.example.demo.controller.UserController


package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/users")
public class UserController {

  private final UserMapper userMapper;

  @Autowired
  public UserController(UserMapper userMapper) {
    this.userMapper = userMapper;
  }

  /**
   *Anzeige des Listenbildschirms
   */
  @GetMapping
  public String getUsers(Model model) {
    List<User> users = userMapper.selectAll();
    model.addAttribute("users", users);
    return "users/list";
  }

  /**
   *Bildschirm mit Details anzeigen
   */
  @GetMapping("{id}")
  public String getUser(@PathVariable int id, Model model) {
    User user = userMapper.select(id);
    model.addAttribute("user", user);
    return "users/show";
  }

  /**
   *Anzeige des neuen Erstellungsbildschirms
   */
  @GetMapping("new")
  public String getUserNew(Model model) {
    User user = new User();
    model.addAttribute("user", user);
    return "users/new";
  }

  /**
   *Fügen Sie die Verarbeitung des neuen Erstellungsbildschirms ein
   */
  @PostMapping
  public String postUserCreate(@ModelAttribute @Valid User user,
      BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      return "users/new";
    }
    userMapper.insert(user);
    return "redirect:/users";
  }

  /**
   *Anzeige des Bearbeitungsbildschirms
   */
  @GetMapping("{id}/edit")
  public String getUserEdit(@PathVariable int id, Model model) {
    User user = userMapper.select(id);
    model.addAttribute("user", user);
    return "users/edit";
  }

  /**
   *Bildschirmaktualisierungsprozess bearbeiten
   */
  @PutMapping("{id}")
  public String putUserEdit(@PathVariable int id, @ModelAttribute @Valid User user,
      BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
      return "users/edit";
    }
    user.setId(id);
    userMapper.update(user);
    return "redirect:/users";
  }

  /**
   *Prozess löschen
   */
  @DeleteMapping("{id}")
  public String deleteUser(@PathVariable int id, Model model) {
    userMapper.delete(id);
    return "redirect:/users";
  }
}

Einstellungen für Validierungsnachrichten (messages.properties, WebConfig.java erstellt)

--Erstellen Sie messages.properties, um Validierungsnachrichten festzulegen.

src/main/resources/messages.properties


name=Nutzername
require_check={0}Ist ein erforderlicher Eintrag

java:com.example.demo/WebConfig.java


package com.example.demo;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class WebConfig {

  @Bean
  public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
    bean.setBasename("classpath:messages");
    bean.setDefaultEncoding("UTF-8");
    return bean;
  }

  @Bean
  public LocalValidatorFactoryBean localValidatorFactoryBean() {
    LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
    localValidatorFactoryBean.setValidationMessageSource(messageSource());
    return localValidatorFactoryBean;
  }
}

Bildschirmerstellung (Layout, Show, Liste, Neu, Bearbeiten, Formular, CSS-Erstellung)

Gemeinsames Layout (layout.html)

--Inhalte werden in <div layout: fragment =" content "> </ div> angezeigt.

src/main/resources/templates/commons/layout.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" >

<head>
    <meta charset="UTF-8">
    <link th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet"/>
    <script th:src="@{/webjars/jquery/1.11.1/jquery.min.js}"></script>
    <script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
    <link th:href="@{/css/home.css}" rel="stylesheet"/>
    <title>Home</title>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">SpringMyBatisDemo</a>
        </div>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-2 sidebar">
            <ul class="nav nav-pills nav-stacked">
                <li role="presentation"><a th:href="@{/users}">Benutzerverwaltung</a></li>
            </ul>
        </div>
    </div>
</div>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-10 col-sm-offset-2 main">
            <div layout:fragment="contents">

            </div>
        </div>
    </div>
</div>

</body>
</html>

Listenbildschirm (list.html)

--Layout wird mit layout: decorate =" ~ {commons / layout} " verwendet.

src/main/resources/templates/users/list.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{commons/layout}">

<head>
  <meta charset="UTF-8">
  <link th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet"/>
  <script th:src="@{/webjars/jquery/1.11.1/jquery.min.js}"></script>
  <script th:src="@{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
  <link th:href="@{/css/home.css}" rel="stylesheet"/>
  <title>Home</title>
</head>
<body>
<div layout:fragment="contents">
  <div class="page-header">
    <h1>Benutzerliste</h1>
  </div>
  <table class="table table-bordered table-hover table-striped">
    <tr>
      <th class="info col-sm-2">Benutzeridentifikation</th>
      <th class="info col-sm-2">Nutzername</th>
      <th class="info col-sm-2"></th>
    </tr>
    <tr th:each="user:${users}">
      <td th:text="${user.id}"></td>
      <td th:text="${user.name}"></td>
      <td>
        <a class="btn btn-primary" th:href="@{'/users/' + ${user.id}}">Einzelheiten</a>
        <a class="btn btn-primary" th:href="@{'/users/' + ${user.id} + '/edit'}">Bearbeiten</a>
      </td>
    </tr>
  </table>
  <label class="text-info" th:text="${result}">Ergebnisanzeige</label><br/>
  <a class="btn btn-primary" th:href="${'/users/new'}">Erstelle neu</a>
</div>

</body>
</html>

Detailbildschirm (show.html)

--Layout wird mit layout: decorate =" ~ {commons / layout} " verwendet.

src/main/resources/templates/users/show.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{commons/layout}">

<head>
  <meta charset="UTF-8"/>
  <title></title>
</head>
<body>
<div layout:fragment="contents">
  <div class="row">
    <div class="col-sm-5">
      <div class="page-header">
        <div>
          <h1>Nutzerdetails</h1>
        </div>
          <table class="table table-bordered table-hover">
            <tr>
              <th class="active col-sm-3">Nutzername</th>
              <td>
                <div class="form-group" th:object="${user}">
                  <label class="media-body" th:text="*{name}">
                  </label>
                </div>
              </td>
            </tr>
          </table>
        <form th:action="@{/users}" th:method="get">
          <button class="btn btn-primary btn-lg pull-right" type="submit">Aufführen</button>
        </form>
      </div>
    </div>
  </div>
</div>
</body>
</html>

Bildschirm bearbeiten (edit.html)

--Layout wird mit layout: decorate =" ~ {commons / layout} " verwendet.

src/main/resources/templates/users/edit.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{commons/layout}">

<head>
  <meta charset="UTF-8"/>
  <title></title>
</head>
<body>
<div layout:fragment="contents">
  <div class="row">
    <div class="col-sm-5">
      <div class="page-header">
        <div>
          <h1>Nutzerdetails</h1>
        </div>
        <form th:action="@{/users/{id}(id=*{id})}" th:method="put" th:object="${user}">

          <div th:include="users/form :: form_contents"></div>

          <button class="btn btn-primary btn-lg pull-right" type="submit">aktualisieren</button>
        </form>
        <form th:action="@{/users/{id}(id=*{id})}" th:method="delete" th:object="${user}">
          <button class="btn btn-danger btn-lg" type="submit">Löschen</button>
        </form>
      </div>
    </div>
  </div>
</div>
</body>
</html>

Neuer Bildschirm (new.html)

--Layout wird mit layout: decorate =" ~ {commons / layout} " verwendet.

src/main/resources/templates/users/new.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{commons/layout}">

<head>
  <meta charset="UTF-8"/>
  <title></title>
</head>
<body>
<div layout:fragment="contents">
  <div class="row">
    <div class="col-sm-5">
      <div class="page-header">
        <div>
          <h1>Neuen Benutzer erstellen</h1>
        </div>
        <form method="post" th:action="@{/users}" th:object="${user}">

          <div th:include="users/form :: form_contents"></div>

          <button class="btn btn-primary btn-lg pull-right" type="submit" name="update">Erstellen</button>
        </form>
      </div>
    </div>
  </div>
</div>
</body>
</html>

Gemeinsame Form

src/main/resources/templates/users/form.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
  <meta charset="UTF-8"/>
  <title></title>
</head>
<body>
<div th:fragment="form_contents">
  <table class="table table-bordered table-hover">
    <tr>
      <th class="active col-sm-3">Nutzername</th>
      <td>
        <div class="form-group" th:classappend="${#fields.hasErrors('name')} ? 'has-error'">
          <label>
            <input type="text" class="form-control" th:field="*{name}"/>
          </label>
          <span class="text-danger" th:if="${#fields.hasErrors('name')}"
                th:errors="*{name}">Name error</span>
        </div>
      </td>
    </tr>
  </table>
</div>
</body>
</html>

css

src/main/resources/static/css/home.css


body {
    padding-top: 50px;
}

.sidebar {
    position: fixed;
    display: block;
    top: 50px;
    bottom: 0;
    background-color: #F4F5F7;
}

.main {
    padding-top: 50px;
    padding-left: 20px;
    position: fixed;
    display: block;
    top: 0;
    bottom: 0;
}

.page-header {
    margin-top: 0;
}

image.png

image.png

image.png

--Referenz

Recommended Posts

Erstellen Sie eine CRUD-App mit Spring Boot 2 + Thymeleaf + MyBatis
Implementieren Sie CRUD mit Spring Boot + Thymeleaf + MySQL
Erstellen Sie Ihr eigenes Dienstprogramm mit Thymeleaf mit Spring Boot
Erstellen Sie mit Spring Boot einen Mikrodienst
Erstellen Sie eine App mit Spring Boot 2
Erstellen Sie eine App mit Spring Boot
Implementieren Sie die Paging-Funktion mit Spring Boot + Thymeleaf
Führen Sie die WEB-Anwendung mit Spring Boot + Thymeleaf aus
Erstellen Sie eine Website mit Spring Boot + Gradle (jdk1.8.x)
Bis zur Datenerfassung mit Spring Boot + MyBatis + PostgreSQL
Erstellen Sie mit Spring Boot eine einfache Such-App
Verwendung von MyBatis2 (iBatis) mit Spring Boot 1.4 (Spring 4)
Erstellen Sie eine Spring Boot-Umgebung mit Windows + VS-Code
Erstellen Sie einen Web-API-Server mit Spring Boot
Mit Spring Boot herunterladen
Erstellen Sie mit Docker eine Spring Boot-Entwicklungsumgebung
Erstellen Sie mit Spring Boot 2.0 einen Spring Cloud Config Server mit Sicherheit
Erstellen Sie Restapi mit Spring Boot (bis zum Ausführen der App)
Erstellen Sie mit Spring Security 2.1 eine einfache Demo-Site mit Spring Security
Generieren Sie mit Spring Boot einen Barcode
Hallo Welt mit Spring Boot
Implementieren Sie GraphQL mit Spring Boot
Beginnen Sie mit Spring Boot
Hallo Welt mit Spring Boot!
Führen Sie LIFF mit Spring Boot aus
SNS-Login mit Spring Boot
[Java] Thymeleaf Basic (Spring Boot)
Datei-Upload mit Spring Boot
Spring Boot beginnt mit dem Kopieren
Spring Boot beginnend mit Docker
Hallo Welt mit Spring Boot
Setzen Sie Cookies mit Spring Boot
Verwenden Sie Spring JDBC mit Spring Boot
Modul mit Spring Boot hinzufügen
Erste Schritte mit Spring Boot
Mail mit Spring Boot verschicken
Behandeln Sie die Java 8-Datums- und Uhrzeit-API mit Thymeleaf mit Spring Boot
Erstellen Sie eine einfache CRUD mit SpringBoot + JPA + Thymeleaf ~ ~ Validierung hinzufügen ~
Bis INSERT und SELECT für Postgres mit Spring Boot und Thymianblatt
Stellen Sie mit spring boot + spring jpa eine Verbindung zur Datenbank her und führen Sie die CRUD-Operation durch
Verwenden Sie thymeleaf3 mit parent, ohne Spring-Boot-Starter-Parent in Spring Boot anzugeben
Verwenden Sie die Standardauthentifizierung mit Spring Boot
gRPC auf Spring Boot mit grpc-spring-boot-Starter
Hot Deploy mit Spring Boot-Entwicklung
Datenbankverknüpfung mit doma2 (Spring Boot)
Spring Boot Programmierung mit VS Code
Bis "Hallo Welt" mit Spring Boot
Erstellen Sie eine Anfrage-App mit Spring Boot
Erhalten Sie Validierungsergebnisse mit Spring Boot
Google Cloud Platform mit Spring Boot 2.0.0
Ich habe GraphQL mit Spring Boot ausprobiert
[Java] LINE-Integration mit Spring Boot
Beginnend mit Spring Boot 0. Verwenden Sie Spring CLI
Ich habe Flyway mit Spring Boot ausprobiert
Zertifizierung / Autorisierung mit Spring Security & Thymeleaf
Verwendung von Thymeleaf mit Spring Boot
Die Nachrichtenkooperation begann mit Spring Boot
Erstellen Sie eine einfache CRUD mit SpringBoot + JPA + Thymeleaf ④ ~ Fehlermeldung anpassen ~
So erstellen Sie mit Spring Boot einen eigenen Controller, der / error entspricht