App下載

MyBatis中@param()注解而產(chǎn)生的分頁(yè)失效問(wèn)題 附詳細(xì)解決方案

猿友 2021-08-05 12:33:59 瀏覽數(shù) (3213)
反饋

本篇文章將為大家介紹一個(gè)在使用MyBatis的過(guò)程,因?yàn)樽⒔釦param()而產(chǎn)生的分頁(yè)失效的問(wèn)題,以及具體解決該問(wèn)題的方法,希望能夠?qū)Υ蠹业膶W(xué)習(xí)和工作有所幫助!

問(wèn)題描述

在使用mybatis分頁(yè)時(shí),使用@Param注解傳入了兩個(gè)對(duì)象,分頁(yè)失效,查詢出的總是全部的數(shù)據(jù)。
出現(xiàn)問(wèn)題時(shí),分頁(yè)策略為:分頁(yè)攔截器實(shí)現(xiàn)的分頁(yè)

【錯(cuò)誤寫(xiě)法】

service寫(xiě)法:

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>

原因解析

【關(guān)鍵原因】

  • 根源問(wèn)題在于:在PaginationInterceptor中,分頁(yè)對(duì)象Page被解析為null,導(dǎo)致的分頁(yè)失效
  • 由于@Param會(huì)將參數(shù)封裝到ParamMap中,而page對(duì)象在實(shí)體類entity中,導(dǎo)致convertParameter方法返回的page對(duì)象為null

20210413105204192

【mybatis原碼:@Param將參數(shù)封裝到ParamMap】

跟蹤源碼進(jìn)入:org.apache.ibatis.binding.MapperMethod.class

20210413105204193

進(jìn)入executeForMany方法:

20210413105204194

進(jìn)入convertArgsToSqlCommandParam方法,可以看到參數(shù)封裝到ParamMap中:

20210413105205195

解決辦法

  • 不使用@Param注解:在傳遞多個(gè)參數(shù)(或是多個(gè)javaBean)時(shí),可以使用一個(gè)包含page屬性的實(shí)體類進(jìn)行封裝
  • 使用@Param注解:根據(jù)需求修改BaseInterceptor類中的convertParameter方法,使得解析page對(duì)象不為null即可

到此這篇關(guān)于MyBatis的注解@param()而導(dǎo)致分頁(yè)失效的問(wèn)題以及具體解決方案的文章就介紹到這了,想要了解更多相關(guān)MyBatis的內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持!

0 人點(diǎn)贊