基于springboot+mybtais写一个通用的分页查询接口
时间: 2024-01-20 15:04:09 浏览: 144
springboot整合mybatis-plus实现多表分页查询
好的,我了解了你的要求。对于你的问题,我们可以通过以下步骤来实现一个基于 SpringBoot 和 MyBatis 的通用分页查询接口:
1. 首先,在 pom.xml 文件中添加 SpringBoot 和 MyBatis 的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2. 创建一个分页查询的接口 PageableMapper:
```
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import java.util.List;
public interface PageableMapper<T> {
List<T> page(@Param("offset") int offset, @Param("limit") int limit);
List<T> page(@Param("offset") int offset, @Param("limit") int limit, @Param("param") Object param);
List<T> page(@Param("offset") int offset, @Param("limit") int limit, @Param("param") Object param, RowBounds rowBounds);
List<T> page(@Param("offset") int offset, @Param("limit") int limit, @Param("param") Object param, String orderBy, RowBounds rowBounds);
int count();
int count(@Param("param") Object param);
}
```
3. 创建一个分页查询的通用实现类 PageableMapperImpl:
```
import org.apache.ibatis.session.RowBounds;
import java.util.List;
public class PageableMapperImpl<T> implements PageableMapper<T> {
private Mapper<T> mapper;
public PageableMapperImpl(Mapper<T> mapper) {
this.mapper = mapper;
}
@Override
public List<T> page(int offset, int limit) {
return mapper.selectPage(offset, limit);
}
@Override
public List<T> page(int offset, int limit, Object param) {
return mapper.selectPage(offset, limit, param);
}
@Override
public List<T> page(int offset, int limit, Object param, RowBounds rowBounds) {
return mapper.selectPage(offset, limit, param, rowBounds);
}
@Override
public List<T> page(int offset, int limit, Object param, String orderBy, RowBounds rowBounds) {
return mapper.selectPage(offset, limit, param, orderBy, rowBounds);
}
@Override
public int count() {
return mapper.selectCount();
}
@Override
public int count(Object param) {
return mapper.selectCount(param);
}
}
```
4. 创建一个 Mapper Interface,例如:
```
public interface UserMapper extends Mapper<User> {
}
```
5. 在 Service 中调用分页查询接口:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findByPage(int pageNum, int pageSize) {
PageableMapper<User> pageableMapper = new PageableMapperImpl<>(userMapper);
int start = (pageNum - 1) * pageSize;
return pageableMapper.page(start, pageSize);
}
}
```
这样就可以在 Service 中调用通用的分页查询接口了。
阅读全文