PageHelper集成SpringBoot

一、引入依赖


        
            com.github.pagehelper
            pagehelper
            4.1.6
        

二、在Spring Boot启动类中添加bean

package com.yilong.mp;

import com.github.pagehelper.PageHelper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.Properties;

/**
 * @auther xinye
 * @create 2018 3 7
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum","true");
        properties.setProperty("rowBoundsWithCount","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("dialect","mysql");    //配置mysql数据库的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

三、分页插件的使用



@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {

    @Override
    public UserListResultResp getUserList(String token, Integer pageNo, Integer pageSize) {
        tokenValidateHelper.validate(token);
        Page page = PageHelper.startPage(pageNo,pageSize,true);//第三个参数为true则返回总的记录数
        List userList = userMapper.getAllUser();//要注意的是,这一行最好跟在上面那一行代码之后,否则可能导致分页错乱
        if(userList != null) {
            List userListResps = new ArrayList<>();
            for(UserModel user : userList) {
                UserListResp resp = new UserListResp(user.getUserId(),user.getHeadImg(),user.getNickName(),user.getMobile(),user.getAddress());
                userListResps.add(resp);
            }
            UserListResultResp userListResultResp = new UserListResultResp();
            userListResultResp.setUserList(userListResps);
            userListResultResp.setRowCount(page.getTotal());
            return userListResultResp;
        }else {
            throw new ApiException(ResponseErr.DATA_ERROR);
        }
    }
}

你可能感兴趣的:(PageHelper集成SpringBoot)