1、導入相關依賴 (PageHelper自帶了mybatis、mybatis-spring,不排除會報錯)
<!-- pagehelper分頁插件依賴 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.10</version> <exclusions> <exclusion> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </exclusion> <exclusion> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </exclusion> </exclusions> </dependency>
2、在application.yml 配置文件中配置指定數據庫
#pagehelper配置
pagehelper: helper-dialect: mysql
其他相關配置:https://www.cnblogs.com/mengw/p/11673637.html
或者使用配置類
3、使用Pagehelper多條件分頁
條件類:
@Data @AllArgsConstructor @NoArgsConstructor public class HouseQueryInfo implements Serializable{ private static final long serialVersionUID = 1034989291292817460L; //private int pageIndex;//當前頁碼(頁面傳遞) //private int pageSize;//頁容量(后台設置) private String title; private String price_on; private String price_down; private String street_id; private String type_id; private String floorage_on; private String floorage_down; }
service層接口:
public interface IHouseService extends IService<House>{ //根據條件查詢所有房屋信息,分頁顯示 List<House> findAllHouse(HouseQueryInfo houseInfo) throws Exception; //使用pagehelper分頁查詢 public PageInfo<House> findBookPage(Integer pageIndex,Integer pageSize,HouseQueryInfo houseInfo) throws Exception; }
serviceimpl實現類:
@Service public class HouseServiceImpl extends ServiceImpl<IHouseMapper, House> implements IHouseService { @Autowired private IHouseMapper houseMapper; //根據條件查詢所有房屋信息,分頁顯示 @Override public List<House> findAllHouse(HouseQueryInfo houseInfo) throws Exception { return houseMapper.findAllHouse(houseInfo); } //根據所有信息進行分頁 @Override public PageInfo<House> findBookPage(Integer pageIndex,Integer pageSize,HouseQueryInfo houseInfo) throws Exception { PageHelper.startPage(pageIndex,pageSize); PageInfo<House> pageinfo = new PageInfo<>(houseMapper.findAllHouse(houseInfo)); return pageinfo; }
controller層:
PageInfo<House> pageInfo = houseService.findBookPage(houseInfoVo.getPageIndex(),3,houseInfo); // 將租房信息存入model中 model.addAttribute("pageInfo", pageInfo);
頁面數據的展示:
<TR th:each="house:${pageInfo.getList()}"> <TD class=house-thumb><span> <img th:src="${house.photopath != null} ? |/img/${house.photopath}| :'../images/thumb_house.gif' " width="100" height="75"</span></TD> <TD> <DL> <DT> <A href="#" th:text="${house.title}"></A> </DT> <DD> <span th:text="${house.streets.name}"/> <span th:text="${house.streets.district.name}"/> <span th:text="${house.floorage}"/> 平米<BR>聯系方式:<span th:text="${house.contact}"/> </DD> </DL> </TD> <TD class=house-type><span th:text="${house.typess.name}"/></TD> <TD class=house-price><SPAN th:text="${house.price}"></SPAN>元/月</TD> </TR>