Spring Boot學習筆記(九)Spring Boot Jpa 與 Thymeleaf 實現增刪改查

Spring Boot Jpa 與 Thymeleaf 實現增刪改查

  • 源碼鏈接:https://github.com/StephaineWYT/JpaThymeleafDemo
  • 初始化Spring項目 :https://start.spring.io/

    在這裏插入圖片描述

  • 解壓後用IDEA打開,建立項目結構如下:

    在這裏插入圖片描述

  • pom.xml:

    先點擊右下方提示:Enable-AutoImport

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>wen</groupId>
        <artifactId>JpaThymeleafDemo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>JpaThymeleafDemo</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    
  • 數據庫配置文件,記得根據自己的數據庫賬號密碼以及url修改
    spring.datasource.url=jdbc:mysql://localhost:3306/jtl?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone = GMT
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.jpa.properties.hibernate.hbm2ddl.auto=update
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.jpa.show-sql=true
    spring.thymeleaf.cache=false
    
  • 注:存在上述jtl數據庫即可,Spring Boot會根據實體類自動創建表
  • 實體類 model.User.java:
    package wen.JpaThymeleafDemo.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Entity
    public class User {
    
        @Id
        @GeneratedValue
        private long id;
    
        @Column(nullable = false, unique = true)
        private String username;
    
        @Column(nullable = false)
        private String password;
    
        @Column(nullable = false)
        private int age;
    
        public long getId() {
            return id;
        }
    
        public User setId(long id) {
            this.id = id;
            return this;
        }
     
     
        public String getUsername() {
            return username;
        }
    
        public User setUsername(String username) {
            this.username = username;
            return this;
        }
    
        public String getPassword() {
            return password;
        }
    
        public User setPassword(String password) {
            this.password = password;
            return this;
        }
    
        public int getAge() {
            return age;
        }
    
        public User setAge(int age) {
            this.age = age;
            return this;
        }
    }
    
  • UserRepository.java: 定義查和刪兩個接口用於service層調用
    package wen.JpaThymeleafDemo.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import wen.JpaThymeleafDemo.model.User;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    
        User findById(long id);
    
        void deleteById(Long id);
    }
    
    
  • UserService.java: 定義兩個增刪改查的五個接口,用於controller層調用
    package wen.JpaThymeleafDemo.service;
    
    import wen.JpaThymeleafDemo.model.User;
    
    import java.util.List;
    
    public interface UserService {
    
        List<User> getUserList();
    
        User findUserById(long id);
    
        void save(User user);
    
        void edit(User user);
    
        void delete(long id);
    }
    
    
  • UserServiceImpl.java
    package wen.JpaThymeleafDemo.service.impl;
    
    import wen.JpaThymeleafDemo.model.User;
    import wen.JpaThymeleafDemo.repository.UserRepository;
    import wen.JpaThymeleafDemo.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public List<User> getUserList() {
            return userRepository.findAll();
        }
    
        @Override
        public User findUserById(long id) {
            return userRepository.findById(id);
        }
    
        @Override
        public void save(User user) {
            userRepository.save(user);
        }
    
        @Override
        public void edit(User user) {
            userRepository.save(user);
        }
    
        @Override
        public void delete(long id) {
            userRepository.deleteById(id);
        }
    }
    
    
  • UserController:
    package wen.JpaThymeleafDemo.web;
    
    import wen.JpaThymeleafDemo.model.User;
    import wen.JpaThymeleafDemo.service.UserService;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @Controller
    public class UserController {
    
        @Resource
        UserService userService;
    
    
        @RequestMapping("/")
        public String index() {
            return "redirect:/list";
        }
    
        @RequestMapping("/list")
        public String list(Model model) {
            List<User> users = userService.getUserList();
            model.addAttribute("users", users);
            return "user/list";
        }
    
        @RequestMapping("/toAdd")
        public String toAdd() {
            return "user/userAdd";
        }
    
        @RequestMapping("/add")
        public String add(User user) {
            userService.save(user);
            return "redirect:/list";
        }
    
        @RequestMapping("/toEdit")
        public String toEdit(Model model, Long id) {
            User user = userService.findUserById(id);
            model.addAttribute("user", user);
            return "user/userEdit";
        }
    
        @RequestMapping("/edit")
        public String edit(User user) {
            userService.edit(user);
            return "redirect:/list";
        }
    
    
        @RequestMapping("/delete")
        public String delete(Long id) {
            userService.delete(id);
            return "redirect:/list";
        }
    }
    
    
  • 接下來配置前端文件:

    在這裏插入圖片描述

  • boostrap.css

    因爲有8000多行,鏈接:https://pan.baidu.com/s/1-AlRxMV0tpkkeKMo0SYlKg
    提取碼:r71q

  • list.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>userList</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>用戶列表</h1>
    <br/><br/>
    <div class="with:80%">
        <table class="table table-hover">
            <thead>
            <tr>
                <th>id</th>
                <th>username</th>
                <th>password</th>
                <th>age</th>
                <th>edit</th>
                <th>delete</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="user : ${users}">
                <th scope="row" th:text="${user.id}">1</th>
                <td th:text="${user.username}">neo</td>
                <td th:text="${user.password}">Otto</td>
                <td th:text="${user.age}">6</td>
                <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
                <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="form-group">
        <div class="col-sm-2 control-label">
            <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
        </div>
    </div>
    
    </body>
    </html>
    
  • userAdd.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}">
    </head>
    <body class="container">
    <br/>
    <h1>添加用戶</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal" th:action="@{/add}" method="post">
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">username</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" id="username" placeholder="username"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="password" id="password" placeholder="password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age" id="age" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info"/>
                    &nbsp; &nbsp; &nbsp;
                    <input type="reset" value="Reset" class="btn btn-info"/>
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    
    
  • userEdit.html:
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>修改用戶</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal" th:action="@{/edit}" th:object="${user}" method="post">
            <input type="hidden" name="id" th:value="*{id}"/>
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">username</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" id="username" th:value="*{username}"
                           placeholder="username"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label">password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="password" id="password" th:value="*{password}"
                           placeholder="password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info"/>
                    &nbsp; &nbsp; &nbsp;
                    <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    
    
  • 啓動項目

    在這裏插入圖片描述

  • 訪問 http://localhost:8080/list

    在這裏插入圖片描述
    添加在這裏插入圖片描述
    查看
    在這裏插入圖片描述
    啓動的時候如果Tests測試類瘋狂報錯,就刪了吧,反正這個項目用不到
    下一篇:Spring Boot學習筆記(十)Spring Boot 集成 MyBatis —— 概念篇

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章