使用mybatis的分页插件完成分页查询的dao层service层和controller层代码怎么写
时间: 2024-04-06 21:12:46 浏览: 52
mybatis分页插件代码
首先在pom.xml中引入mybatis分页插件的依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
```
然后在mybatis-config.xml中配置分页插件:
```xml
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<property name="reasonable" value="true"/>
</plugin>
</plugins>
```
接下来是dao层的代码,使用PageHelper.startPage方法指定分页参数,然后调用mapper的查询方法即可:
```java
public interface UserDao {
List<User> findUsers(int pageNum, int pageSize);
}
public class UserDaoImpl implements UserDao {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findUsers(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return userMapper.findUsers();
}
}
```
service层的代码也很简单,直接调用dao层的方法即可:
```java
public interface UserService {
PageInfo<User> findUsers(int pageNum, int pageSize);
}
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public PageInfo<User> findUsers(int pageNum, int pageSize) {
List<User> users = userDao.findUsers(pageNum, pageSize);
return new PageInfo<>(users);
}
}
```
最后是controller层的代码,接收分页参数pageNum和pageSize并调用service层的方法:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public PageInfo<User> findUsers(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
return userService.findUsers(pageNum, pageSize);
}
}
```
这样就完成了使用mybatis分页插件进行分页查询的代码实现。
阅读全文