前端代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>删除数据</title>
</head>
<body>
    <h1>删除数据</h1>
    <form method="post" th:action="@{/delete}">
        <label>ID:<input type="text" name="id"></label><br><br>
        <input type="submit" value="删除">
    </form>
</body>
</html>

后端代码:

@Controller
public class DeleteController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/delete")
    public String deletePage() {
        return "delete";
    }

    @PostMapping("/delete")
    public String deleteUser(@RequestParam Long id) {
        userRepository.deleteById(id);
        return "redirect:/delete";
    }

}

其中,UserRepository是一个继承JpaRepository的接口,用于操作数据库中的数据。

public interface UserRepository extends JpaRepository<User, Long> {
}

其中,User是一个实体类,用于映射数据库中的数据。

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    // 省略 getter 和 setter 方法

}

需要注意的是,需要在application.properties中配置数据库相关信息,如下所示:

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
``
通过前端传过来的id删除数据库中的一栏前端用Thymeleaf后端用springboot + jpa 完整代码

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

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