SpringBoot使用Pageable实现分页

  由于在项目中要求使用Pageable实现分页查询,就简单学习了一下。

  在此记录一下操作案例。

Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "key");

  下面简单介绍一下上面的这一行代码:

Pageable 必须引用spring的包。否则后面是不能new PageRequest的!!!!
在这里插入图片描述
在这里插入图片描述
page即当前页。

size代表每页有几条记录。

第三个参数是排序字段, Sort.Direction.DESC是倒序的意思。

最后一个参数是排序关键字,将按照这个关键字进行排序。

  介绍完这个方法本身,下面介绍数据库操作。使用Pageable 时不能使用原生sql。官网说能,我也百度了许多的例子,都运行不起来。下面讲我的办法:

@Query(" from LoginTable k where k.loginName = ?1")
    public Page<LoginTable> getLoginInfo(String loginName, Pageable pageable);

不用在@Query中使用value=nativeQuery = true

形参里面加一个Pageable pageable

使用实体类的类型:LoginTable ,而不是数据库类型:login_table

接收参数使用Page<>,而不是List<>

表名起别名,通过别名去调用。(我遇到的问题,不起别名调不到)

  数据库操作介绍完了,下面介绍一下调用:

Page<LoginTable> pageList = loginRepository.getLoginInfo(loginName,pageable);

依旧使用Page接收

形参加pageable(此时的pageable应该是已经定义好的,有当前页,页容量,排序字段等属性)

Spring Boot整合MyBatis实现分页通常涉及以下几个步骤: 1. **引入依赖**:在`pom.xml`文件中添加MyBatis和分页插件的依赖,如`mybatis-spring-boot-starter`和`pagehelper`。 ```xml <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency> </dependencies> ``` 2. **配置MyBatis**:在`application.properties`或`application.yml`中设置数据源和其他MyBatis配置,包括SqlSessionFactoryBean。 ```properties spring.datasource.type=com.zaxxer.hikari.HikariDataSource mybatis.mapperLocations=classpath:mapper/*.xml mybatis.config-location=classpath:mybatis-config.xml ``` 3. **创建Mapper接口**:定义包含分页查询方法的Mapper接口,例如: ```java import org.apache.ibatis.annotations.*; public interface UserMapper { @Select("SELECT * FROM user LIMIT #{offset}, #{limit}") List<User> list(@Param("offset") int offset, @Param("limit") int limit); } ``` 4. **启用分页插件**:在`mybatis-config.xml`中启用PageHelper,并配置相关属性(如页面大小、SQL方言等)。 ```xml <configuration> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="helperDialect" value="mysql"/> <!-- 其他可选配置 --> </plugin> </plugins> </configuration> ``` 5. **在服务层调用分页查询**:通过@Autowired注入UserMapper并使用其提供的方法获取分页结果。 ```java @Service public class UserService { private final UserMapper userMapper; @Autowired public UserService(UserMapper userMapper) { this.userMapper = userMapper; } public PageResult<User> getUsers(int pageNum, int pageSize) { return userMapper.list(pageNum, pageSize); // 使用PageResult接收分页结果 } } // 分页对象(如PageResult) public class PageResult<T> extends Wrapper<T[]> implements Pageable { // 实现相关接口的方法 } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值