欢迎关注公众号:天天说编程 免费改简历,资料分享,面试经验分享。私信即可。
【代码】gitee地址:晓风残月一望关河萧索 (catchcode11) - Gitee.com
Service,Controller的数据使用PageInfo<T>封装即可。
关键代码,注意顺序:
先startPage设置参数,后获取数据,否则分页失效。
public PageInfo<User> select(UserParam userParam) {
// 先进行分页;后取数据
PageHelper.startPage(userParam.getPageNum(), userParam.getPageSize());
List<User> list = userMapper.select(userParam.getUsername());
PageInfo<User> pageInfo = new PageInfo<>(list);
return pageInfo;
}
Controller层:
package com.testpage.cn.testpage.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.testpage.cn.testpage.dao.UserMapper;
import com.testpage.cn.testpage.entity.User;
import com.testpage.cn.testpage.param.UserParam;
import com.testpage.cn.testpage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> select(UserParam userParam) {
// 先进行分页;后取数据
PageHelper.startPage(userParam.getPageNum(), userParam.getPageSize());
List<User> list = userMapper.select(userParam.getUsername());
PageInfo<User> pageInfo = new PageInfo<>(list);
return pageInfo;
}
}
Service层:
public interface UserService {
PageInfo<User> select(UserParam userParam);
}
ServiceImpl实现类:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> select(UserParam userParam) {
// 先进行分页;后取数据
PageHelper.startPage(userParam.getPageNum(), userParam.getPageSize());
List<User> list = userMapper.select(userParam.getUsername());
PageInfo<User> pageInfo = new PageInfo<>(list);
return pageInfo;
}
}
dao层:
@Mapper
public interface UserMapper {
List<User> select(@Param("username") String username);
}
entity:
@Data
public class User {
private Integer id;
private String username;
private String password;
}
userParam:
@Data
public class UserParam {
private Integer pageNum = 1;
private Integer pageSize = 3;
private String username;
}
mapper.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">
<!-- namespace指定dao层对应的接口 -->
<mapper namespace="com.testpage.cn.testpage.dao.UserMapper">
<select id="select" resultType="com.testpage.cn.testpage.entity.User" parameterType="string" >
select * from t_user where username = #{username}
</select>
</mapper>
application.yml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
application:
name: SpringBootDemo
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test1111?serverTimezone=Asia/Shanghai
username:
password:
mybatis:
mapper-locations: classpath:mapper/*.xml
server:
port: 8080
欢迎关注公众号:天天说编程 免费改简历,资料分享,面试经验分享。私信即可。