转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/80696898
本文出自【赵彦军的博客】
Mybatis-PageHelper 简介
PageHelper 最方便使用的分页插件,支持多种数据库:
Oracle
Mysql
MariaDB
SQLite
Hsqldb
PostgreSQL
DB2
SqlServer(2005,2008)
Informix
H2
SqlServer2012
Derby
Phoenix
GitHub: https://github.com/pagehelper/Mybatis-PageHelper
依赖添加
buildscript {
ext {
springBootVersion = '2.0.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.yanjun'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter',
'org.springframework.boot:spring-boot-starter-web',
)
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime('mysql:mysql-connector-java') //mysql驱动
compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0'
compile 'com.github.pagehelper:pagehelper-spring-boot-starter:1.2.3' //pagehelper
}
配置文件 application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
sql-script-encoding: UTF-8
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
server:
port: 8023
实战演练
创建实体类 User
public class User {
Integer id;
String name;
Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
创建 Mapper 类 UserMapper
public interface UserMapper {
@Select("select * from user")
List<User> findAll();
}
创建 service 类 UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public PageInfo findAll(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.findAll();
PageInfo<User> pageInfo = new PageInfo<>(userList);
return pageInfo;
}
}
创建 controller 类 UserController
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("findAll")
public PageInfo getUser(int pageNum, int pageSize) {
return userService.findAll(pageNum,pageSize);
}
}
添加扫包注解
@SpringBootApplication
@MapperScan("com.yanjun.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
效果测试
总结
本文所有代码已经上传至 GitHub ,分支 PageHelper
地址: https://github.com/zyj1609wz/SpringBootMybatis
个人微信号:zhaoyanjun125 , 欢迎关注