1. 在实体类中添加@Id注解,表示该字段为主键
@Entity
public class Data {
    @Id
    private Long id;
    ...
}
  1. 在Repository接口中添加删除方法,使用@Query注解指定SQL语句
@Repository
public interface DataRepository extends JpaRepository<Data, Long> {
    @Modifying
    @Query("DELETE FROM Data d WHERE d.id = :id")
    void deleteById(@Param("id") Long id);
}
  1. 在Controller中接收前端传过来的id,并调用Repository中的删除方法进行删除操作
@Controller
public class DataController {
    @Autowired
    private DataRepository dataRepository;

    @PostMapping("/delete")
    public String deleteData(@RequestParam("id") Long id) {
        dataRepository.deleteById(id);
        return "redirect:/list"; // 删除后重定向到列表页
    }
}
  1. 在Thymeleaf中添加删除按钮,并将id作为参数传递给Controller的deleteData方法
<table>
    <tr th:each="data : ${datas}">
        <td th:text="${data.id}"></td>
        <td th:text="${data.name}"></td>
        <td>
            <form th:action="@{/delete}" method="post">
                <input type="hidden" name="id" th:value="${data.id}">
                <button type="submit">删除</button>
            </form>
        </td>
    </tr>
</table>
``

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

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