Spring Boot + Thymeleaf + JPA 实现前端页面添加数据到数据库时防止重复数据

本文介绍如何使用 Spring Boot + Thymeleaf + JPA 实现前端页面添加数据到数据库时防止重复数据,并展示了完整的代码示例。

1. 数据库表结构

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_create_time` (`create_time`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

2. 实体类 User.java

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private Integer age;
    @Column(name = "create_time")
    private Date createTime;
    // 省略 getter 和 setter 方法
}

3. 控制器 UserController.java

@Controller
public class UserController {
    @Autowired
    private UserRepository userRepository;
    @GetMapping("/")
    public String index(Model model) {
        List<User> userList = userRepository.findAll();
        model.addAttribute("userList", userList);
        return "index";
    }
    @PostMapping("/addUser")
    public String addUser(User user, Model model) {
        // 判断是否有重复数据
        User existUser = userRepository.findByCreateTime(user.getCreateTime());
        if (existUser != null) {
            model.addAttribute("errorMessage", "该时间已存在,请修改时间!");
            return "index";
        }
        userRepository.save(user);
        return "redirect:/";
    }
}

4. 页面 index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
<h2>用户列表</h2>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>创建时间</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="user : ${userList}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.age}"></td>
        <td th:text="${user.createTime}"></td>
    </tr>
    </tbody>
</table>
<form action="/addUser" method="post">
    <div>
        <label>姓名:</label>
        <input type="text" name="name" required>
    </div>
    <div>
        <label>年龄:</label>
        <input type="number" name="age" required>
    </div>
    <div>
        <label>创建时间:</label>
        <input type="datetime-local" name="createTime" required>
    </div>
    <div>
        <button type="submit">添加</button>
    </div>
    <div th:if="${errorMessage}">
        <p style="color: red;" th:text="${errorMessage}"></p>
    </div>
</form>
</body>
</html>

说明:

  • 在控制器中,使用 UserRepository 的 findByCreateTime 方法查询是否已存在重复数据;
  • 在添加用户的 POST 请求中,如果存在重复数据,则返回到页面,并传递一个错误信息 errorMessage;
  • 在页面中,如果有 errorMessage,则显示错误提示。

本示例代码仅供参考,您可以根据自己的实际需求进行修改和完善。

Spring Boot + Thymeleaf + JPA 实现前端页面添加数据到数据库时防止重复数据

原文地址: https://www.cveoy.top/t/topic/nwZg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录