原来自己写分页,用sql语句limit实现,在mybatis的mapper xml上要写两个重复的sql,一个算count,一个得到具体的bean list。感觉好蠢。
多看别人代码的好处,就是能学习别人的经验。看到有人用PageHelper。这个能简化代码,而且只要一个sql 查询 bean list就可以。插件能帮你实现分页,和 count统计。
具体看下面代码。
xml中引入PageHelper
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.4</version>
</dependency>
springboot注入PageHelper,这个要做,不然分页不生效
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* 分页初始化配置
*/
@Configuration
public class PageHelperConfig {
/**
* 注入pagehelper配置
*/
@Bean
public PageHelper getPageHelper() {
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("dialect", "mysql");
//分页合理化
properties.setProperty("reasonable", "false");
//是否支持接口参数来传递分页参数,默认false
properties.setProperty("supportMethodsArguments", "false");
//当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
properties.setProperty("pageSizeZero", "true");
//RowBounds参数offset作为PageNum使用 - 默认不使用
properties.setProperty("offsetAsPageNum", "false");
//RowBounds是否进行count查询 - 默认不查询
properties.setProperty("rowBoundsWithCount", "false");
properties.setProperty("returnPageInfo", "none");
pageHelper.setProperties(properties);
return pageHelper;
}
}
做数据的分页,在service中实现,page中包含一些 分页的信息,包括count
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.idss.controller.User;
import com.idss.dao.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TestServiceImpl implements TestService{
@Autowired
private TestMapper testMapper;
@Override
public List<User> getUserByCondition(User user) {
PageHelper.startPage(user.getPageNum(),user.getPageSize());
List<User> list = testMapper.getUserByCondition();
PageInfo<User> page = new PageInfo<User>(list);
return page.getList();
}
}