我使用 MySQL 创建了一个用户表,关键字有user_id、user_name、account、password 、phone 、address 、role,请使用 springboot+hibernate+thymeleaf 帮我完成分页查询所有用户的功能,查询到的结果返回user-check.html,包含Controller、DAO、Entity、Service
时间: 2023-07-10 17:05:04 浏览: 143
好的,以下是示例代码。
首先是 Entity 类:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long user_id;
private String user_name;
private String account;
private String password;
private String phone;
private String address;
private String role;
// 省略 getter 和 setter 方法
}
```
然后是 DAO 层:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
接下来是 Service 层:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public Page<User> getUsersByPage(int pageNum, int pageSize) {
Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
return userRepository.findAll(pageable);
}
}
```
最后是 Controller 层:
```java
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user/check")
public String checkUsers(Model model, @RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
Page<User> users = userService.getUsersByPage(pageNum, pageSize);
model.addAttribute("users", users.getContent());
model.addAttribute("currentPage", users.getNumber() + 1);
model.addAttribute("totalPages", users.getTotalPages());
return "user-check";
}
}
```
在 Thymeleaf 模板文件 user-check.html 中,可以使用类似如下的代码来显示查询到的用户列表:
```html
<table>
<thead>
<tr>
<th>user_id</th>
<th>user_name</th>
<th>account</th>
<th>password</th>
<th>phone</th>
<th>address</th>
<th>role</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.user_id}"></td>
<td th:text="${user.user_name}"></td>
<td th:text="${user.account}"></td>
<td th:text="${user.password}"></td>
<td th:text="${user.phone}"></td>
<td th:text="${user.address}"></td>
<td th:text="${user.role}"></td>
</tr>
</tbody>
</table>
<div>
<ul class="pagination">
<li th:class="${currentPage == 1} ? disabled : ''">
<a th:href="@{/user/check(pageNum=1,pageSize=${pageSize})}" aria-label="First">
<span aria-hidden="true">«</span>
</a>
</li>
<li th:class="${currentPage == 1} ? disabled : ''">
<a th:href="@{/user/check(pageNum=${currentPage - 1},pageSize=${pageSize})}" aria-label="Previous">
<span aria-hidden="true"><</span>
</a>
</li>
<li th:class="${currentPage == totalPages} ? disabled : ''">
<a th:href="@{/user/check(pageNum=${currentPage + 1},pageSize=${pageSize})}" aria-label="Next">
<span aria-hidden="true">></span>
</a>
</li>
<li th:class="${currentPage == totalPages} ? disabled : ''">
<a th:href="@{/user/check(pageNum=${totalPages},pageSize=${pageSize})}" aria-label="Last">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</div>
```
以上就是使用 Spring Boot、Hibernate 和 Thymeleaf 实现分页查询所有用户的示例代码了。