您的位置:首页 > 其它

Mybatis分页插件PageHelper如何直接返回PageInfo

2016-07-01 10:45 537 查看
mybatis的分页插件:https://github.com/pagehelper/Mybatis-PageHelper

这个插件很强大,也很易用,唯一的美中不足是:分页查询的时候,只能返回Page或者是List,Page实际上也是List。我们在页面上使用的时候,一般是使用PageInfo,PageHelper插件很贴心的提供了一个Page.toPageInfo()工具方法用来做转换。能不能直接让mapper接口返回PageInfo呢?

看mybatis的文档:http://www.mybatis.org/mybatis-3/zh/configuration.html#objectFactory

MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过参数构造方法来实例化。 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。比如:

// ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
public Object create(Class type) {
return super.create(type);
}
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
return super.create(type, constructorArgTypes, constructorArgs);
}
public void setProperties(Properties properties) {
super.setProperties(properties);
}
public <T> boolean isCollection(Class<T> type) {
return Collection.class.isAssignableFrom(type);
}}
<!-- mybatis-config.xml -->
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
<property name="someProperty" value="100"/>
</objectFactory>
也就是说mybatis在生成返回结果的时候是通过ObjectFactory来搞得,而且ObjectFactory还是可以配置的,有戏!

我们先来看下源码对于select的处理:

















从上面的源码可以看出来,只需要自定义ObjectFactory和ObjectWrapperFactory就能实现!

最终实现的效果:


github地址:https://github.com/xjs1919/PageHelperExt
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: