mybatis实现分页查询(pagehelper插件)

来源:互联网 发布:linux常用shell命令 编辑:程序博客网 时间:2024/04/27 01:06
//easyUI分析<!--    Easyui中datagrid控件要求的数据格式为json数据,要包含total和rows两个属性-->    {"total":2,"rows":[{..},{..}]}<!--    方案一:Map    方案二:封装一个实体类-->//封装实体类<!--因为分页查询在各处都用,所以写在工具工程中-->public Class EasyUiResult{    private Long total;    <!--使用通配符?-->    private List<?> rows;}//分析sql语句select * form items limit 11,30;

PageHelper(mybatis实现的分页插件)

第一步,在Mybatis.xml中配置拦截器插件

//mybatis.xml<!--    原理:PageHelper的实现原理就是一个拦截器    执行时机:Executor执行器与mappedeStatement之间,获取sql语句,添加limit    所以PageHelper.statPage(0,10)要在service方法之前执行--><plugins>    <!--mybatis的分页插件-->    <plugin interceptor="包名.PageHelper">        <!--指定方言,不同数据库的分页关键字不一样-->        <property name="dialect" name="mysql">        </property>    </plugin></plugins>

第二步,编写Service层代码
注意:PageHelper和PageInfo的使用

@AutoWiredprivate ItemMapper itemMapper;public EasyUiResult findItemsByPage(Integer page,Integer rows){    <!--封装查询条件的类-->    ItemExample itemExample =  new ItemExample();    <!--用于返回的对象-->    EasyUiResult easyUiResult = new EasyUiResult();    <!--在查询所有之前,设置当前页和显示个数-->    PageHelper.startPage(page,rows);    List<Item> list = itemMapper.selectByExample(itemExample);    easyUiResult.setRows(list);    <!--PageHelper插件提供获得总数的方法-->    PageInfo<Item> info = new PageInfo(list);    Long total = info.getTotal();    easyUiResult.setTotal(total);     return easyUiResult;}

第三步,编写Controller类
注意:增加ResponseBody注解,讲返回的对象转化成Json对象

@AutoWiredprivate ItemService itemService;@RequestMapping("/list")<!--增加这个注解后,返回的对象自动转化成json对象-->@ResponseBodypublic EasyUiResult aaa(Integer page,Integer rows){    EasyUiResult result = service.selectExample(..);    return result;}
0 0
原创粉丝点击