springboot整合mybatis并使用分页插件pageHelper
一、添加pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
二、配置yml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/ssmuser?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
#标注待解析的mapper的xml文件位置;
#在resources目录下创建mapper文件夹,放UserMapper.xml文件
mapper-locations: classpath:mapper/*.xml
#标注实体类位置
type-aliases-package: com.example.helloword.entity
#控制台打印SQL查询语句
logging:
level:
com.example.helloword.dao: DEBUG
pagehelper:
helper-dialect: mysql #数据库方言
reasonable: true #分页合理化
support-methods-arguments: true #是否支持接口参数来传递分页参数,默认false
page-size-zero: true #当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
params: count=countSql
三、创建User.java实体类
public class User {
private int id;
private String username;
private String password;
private String sex;
private Date birthday;
/**省略了getset方法
*/
}
四、创建UserMapper.java
@Mapper
@Repository
public interface UserMapper {
List<User> selectUserByPage(int pageNum,int pageSize);
}
4.1、Mapper包扫描:
注意:需要在添加@MapperScan(“com.example.helloword.dao”)
如图所示:
五、创建UserMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.helloword.dao.UserMapper"> <!-- 一般为数据表在持久层对应接口的完整路径如(qin.com.mapper.UserMapper.java) -->
<!--id对应mapper接口的方法名
paramterType参数类型可以不写
resultType返回类型必须写
参数对应参考链接:[https://blog.csdn.net/aiwokache/article/details/129110992](https://blog.csdn.net/aiwokache/article/details/129110992)
-->
<select id="selectUserByPage" resultType="User" parameterType="int">
select * from users limit #{param1},#{param2}
</select>
</mapper>
六、创建UserService.java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public PageInfo<User> queryUserAll(int pageNum,int pageSize){
PageHelper.startPage(pageNum,pageSize);
List<User> users = userMapper.selectAllUser();
PageInfo<User> userPageInfo = new PageInfo<>(users);
return userPageInfo;
}
}
七、创建UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/userslist")
public List<User> getUserList(int pageNum,int pageSize){
PageInfo<User> pageInfo = userService.queryUserAll(pageNum, pageSize);
List<User> list = pageInfo.getList();
list.forEach(System.out::println);
return list;
}
}
八、使用postman调用接口进行测试
控制台打印: