本篇文章将为大家介绍一个在使用MyBatis的过程,因为注解@param()而产生的分页失效的问题,以及具体解决该问题的方法,希望能够对大家的学习和工作有所帮助!

问题描述

在使用mybatis分页时,使用@Param注解传入了两个对象,分页失效,查询出的总是全部的数据。

出现问题时,分页策略为:
分页拦截器实现的分页

【错误写法】

service写法:

public Page<Entity> getByNidAndEntity(Page<Entity> page,String nid,Entity entity){
       entity.setPage(page);
       page.setList(dao.getByNidAndEntity(nid,entity));
       return page;
}

dao方法声明:

List<Entity> getByNidAndEntity(@Param("nid") String nid,@Param("entity")Entity entity);

mapper.xml中的sql:

<select id="getByNidAndEntity" resultType="Entity">
      select <include refid="entityColumns" />
      from entity_table et left join other_table ot on et.id = ot.eid
      where ot.nid = #{nid} 
      and et.name = #{entity.name} and et.remarks = #{entity.remarks}
</select>

原因解析

【关键原因】

  • 根源问题在于:在PaginationInterceptor中,分页对象Page被解析为null,导致的分页失效
  • 由于@Param会将参数封装到ParamMap中,而page对象在实体类entity中,导致convertParameter方法返回的page对象为null

【mybatis原码:@Param将参数封装到ParamMap】

跟踪源码进入:org.apache.ibatis.binding.MapperMethod.class

进入executeForMany方法:

进入convertArgsToSqlCommandParam方法,可以看到参数封装到ParamMap中:

解决办法

  • 不使用@Param注解:在传递多个参数(或是多个javaBean)时,可以使用一个包含page属性的实体类进行封装
  • 使用@Param注解:根据需求修改BaseInterceptor类中的convertParameter方法,使得解析page对象不为null即可

到此这篇关于MyBatis的注解@param()而导致分页失效的问题以及具体解决方案的文章就介绍到这了,想要了解更多相关MyBatis的内容,请搜索W3Cschool以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。