20200115 PageHelper
简介
PageHelper是Mybatis通用分页插件。
SpringBoot、Mybatis、PageHelper
- pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
- 编写Mapper
与Mybatis一样
@Mapper
public interface UserMapper {
@Select("select * from user")
Page<User> getAllUsers();
}
- 使用PageHelper
@SpringBootApplication
public class PagehelperApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(PagehelperApplication.class, args);
// ==================== 用法一 =============================
// PageHelper.startPage(1, 2);
// test(ctx);
// ==================== 用法二 =============================
// PageHelper.offsetPage(2,2);
// test(ctx);
// ==================== 用法三 =============================
SqlSessionFactory sessionFactory = ctx.getBean(SqlSessionFactory.class);
System.out.println(sessionFactory);
SqlSession sqlSession = sessionFactory.openSession();
List<User> userList = sqlSession.selectList("study.hwj.pagehelper.user.UserMapper.getAllUsers",null, new RowBounds(0, 2));
System.out.println(userList);
userList.forEach(System.out::println);
}
private static void test(ConfigurableApplicationContext ctx){
System.out.println("======================================");
UserMapper userMapper = ctx.getBean(UserMapper.class);
Page<User> page = userMapper.getAllUsers();
System.out.println(page);
page.forEach(System.out::println);
}
}