我使用 MySQL 创建了一个用户表TbUser,userId类型为Integer,并且使用@GetMapping("/deleteListUsers") public String deleteListUsers(@RequestParam(defaultValue = "1") int pageNum, Model model) { Page<TbUser> page = tbUserService.findUsers(pageNum); List<TbUser> userList = page.getContent(); model.addAttribute("userList", userList); model.addAttribute("currentPage", pageNum); model.addAttribute("totalPages", page.getTotalPages()); return "management/user-delete"; }完成了用户分页查询功能,查询的结果返回了user-delete.html,请帮使用springboot+hibernate+thymeleaf帮助我完删除单个用户的功能,删除操作不做物理删除,只做逻辑删除(0表示未删除,1表示已删除),使用逻辑删除标识列status来记录,包含DAO、Controller、Entity、Service、impl
时间: 2024-02-13 17:03:04 浏览: 96
Spring-ssm 的搭建步骤和 通用 mapper 的使用方法
好的,以下是你所需要的代码:
TbUser Entity类
```
@Entity
@Table(name = "TbUser")
public class TbUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userId;
private String username;
private String password;
private Integer status;
// 省略getter和setter方法
}
```
TbUser DAO接口
```
@Repository
public interface TbUserDao extends JpaRepository<TbUser, Integer> {
Page<TbUser> findAllByStatus(Integer status, Pageable pageable);
}
```
TbUser Service接口
```
public interface TbUserService {
Page<TbUser> findUsers(int pageNum);
void logicDeleteUser(Integer userId);
}
```
TbUser Service实现类
```
@Service
public class TbUserServiceImpl implements TbUserService {
@Autowired
private TbUserDao tbUserDao;
@Override
public Page<TbUser> findUsers(int pageNum) {
Pageable pageable = PageRequest.of(pageNum - 1, 10); // 每页显示10条记录
return tbUserDao.findAllByStatus(0, pageable); // 查询未删除的用户
}
@Override
@Transactional(rollbackFor = Exception.class)
public void logicDeleteUser(Integer userId) {
TbUser tbUser = tbUserDao.findById(userId).orElse(null);
if (tbUser != null) {
tbUser.setStatus(1); // 将用户的状态设置为已删除
tbUserDao.save(tbUser);
}
}
}
```
Controller类
```
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private TbUserService tbUserService;
@GetMapping("/deleteListUsers")
public String deleteListUsers(@RequestParam(defaultValue = "1") int pageNum, Model model) {
Page<TbUser> page = tbUserService.findUsers(pageNum);
List<TbUser> userList = page.getContent();
model.addAttribute("userList", userList);
model.addAttribute("currentPage", pageNum);
model.addAttribute("totalPages", page.getTotalPages());
return "management/user-delete";
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") Integer userId) {
tbUserService.logicDeleteUser(userId);
return "redirect:/user/deleteListUsers";
}
}
```
在user-delete.html中添加删除按钮
```
<table>
<thead>
<tr>
<th>用户ID</th>
<th>用户名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userList}">
<td th:text="${user.userId}"></td>
<td th:text="${user.username}"></td>
<td>
<a th:href="@{/user/deleteUser/{id}(id=${user.userId})}">删除</a>
</td>
</tr>
</tbody>
</table>
```
以上代码实现了逻辑删除单个用户的功能,当点击删除按钮后,会将该用户的状态设置为已删除,并重定向到用户列表页面。
阅读全文