后台代码

1.pom.xml

pom包里面添加jpa和thymeleaf的相关包引用

<?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.5.2</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.tuanzi</groupId>
  <artifactId>springboot-jpa-crud</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-jpa-crud</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-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </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-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>


  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
            </exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

2.application.yml

将application.properties改为 application.yml 添加如下配置

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
    username: root
    password: 你的数据库密码



  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update #必须要有(如果没有,即使启动项目,也不会生成相应的表)



  thymeleaf:
    cache: false

其中thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true。

3.实体类映射数据库表

package com.tuanzi.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;

@Entity
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String password;
    @Column(nullable = false)
    private int age;



}

4.Controller代码

package com.tuanzi.controller;

import com.tuanzi.entity.User;
import com.tuanzi.service.UserService;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

    @Resource
    private 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";
    }
}


return "user/userEdit"; 代表会直接去resources目录下找相关的文件。
return "redirect:/list"; 代表转发到对应的controller,这个示例就相当于删除内容之后自动调整到list请求,然后再输出到页面。

5.Service层代码

package com.tuanzi.service;

import com.tuanzi.entity.User;
import java.util.List;

/**
 * 描述:
 *
 * @author 团子
 * @date 2021/6/27 10:50 上午
 */
public interface UserService {

  List<User> getUserList();

  void save(User user);

  User findUserById(Long id);

  void edit(User user);

  void delete(Long id);
}

6.Service实现层代码

package com.tuanzi.service.impl;

import com.tuanzi.dao.UserRepository;
import com.tuanzi.entity.User;
import com.tuanzi.service.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

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

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public User findUserById(Long id) {
        User user = userRepository.getById(id);
        return user;
    }

    @Override
    public void edit(User user) {
        userRepository.save(user);
    }

    @Override
    public void delete(Long id) {

        userRepository.deleteById(id);

    }


}

7.Dao层

继承JpaRepository类会自动实现很多内置的方法,包括增删改查。

package com.tuanzi.dao;

import com.tuanzi.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}

创建一个 test数据库,启动项目后会自动创建对应的表。

前端代码

在项目resources目录下会有两个文件夹:static目录用于放置网站的静态内容如css、js、图片;templates目录用于放置项目使用的页面模板。

我们在templates下面新建一个user目录,下面新建如下三个页面

1.list(列表)页面

<!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}"/>
</head>
<body class="container">
<br/>
<h1>用户列表</h1>
<br/><br/>
<div class="with:80%">
  <table class="table table-hover">
    <thead>
    <tr>
      <th>#</th>
      <th>User Name</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>

2.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}"></link>
</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>

3.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}"/>
</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 如下图
1.png

2.png

3.png

源码地址

代码地址

Q.E.D.