mybatis 实现查询商品列表的分页

1、首先在 mybatis 的配置文件 sqlMapConfig.xml 文件里面添加分页插件:

<!-- 配置分页插件 -->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--> 
			<!--  在  pageHelper4.0之后,可以自动识别数据库类型,不需要指定数据库,
			 如果指定,则会报错  --> 
        	<!-- <property name="dialect" value="mysql"/> -->
		</plugin>
	</plugins>

2、如果jsp页面上用的是EasyUI 框架的话,由于 EasyUI 框架需要的返回数据类型为(total,rows),所以需要创建一个 pojo,如下:

package com.taotao.common.pojo;

import java.util.List;

public class EUDataGridResult {
	
	private long total;
	private List<?> rows;
	public long getTotal() {
		return total;
	}
	public void setTotal(long total) {
		this.total = total;
	}
	public List<?> getRows() {
		return rows;
	}
	public void setRows(List<?> rows) {
		this.rows = rows;
	}
	
}

3、mapper 层用 mybatis 逆向工程生成

4、service 层:

ItemService 接口:

package com.taotao.service;

import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.pojo.tb_Item;

public interface ItemService {

	//tb_Item getItemById(long itemId);
	EUDataGridResult getItemList(int page,int rows);
}

5、接口实现类

package com.taotao.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.mapper.tb_ItemMapper;
import com.taotao.pojo.tb_Item;
import com.taotao.pojo.tb_ItemExample;
@Service
public class ItemServiceImpl implements ItemService{

	
	//分页显示商品列表
	@Override
	public EUDataGridResult getItemList(int page, int rows) {
		//查询商品列表
		tb_ItemExample example = new tb_ItemExample();
		//分页处理
		PageHelper.startPage(page, rows);
		List<tb_Item> list = itemMapper.selectByExample(example);
		//创建一个返回值对象
		EUDataGridResult result = new EUDataGridResult();
		result.setRows(list);
		//取记录总条数
		PageInfo<tb_Item> pageInfo = new PageInfo<>(list);
		result.setTotal(pageInfo.getTotal());
		return result;
	}

}

猜你喜欢

转载自blog.csdn.net/maxiao1204/article/details/79946441