按照mybatis手册中所说的,association有两种实现方式,嵌套查询和嵌套结果映射。如手册中所述,select方式会带来N+1次查询的问题,考虑到效率问题的话建议使用嵌套结果映射。但是在结合使用rowbounds进行分页的时候嵌套结果映射会报Mapped Statements with nested result mapping cannot be safely constrained by rowbounds异常。经过测试发现是rowbounds和resultmap-association之间有冲突,鱼与熊掌不可兼得的话,我想最好还 是选择放弃rowbounds。毕竟可以在sql语句里面加入变量来实现分页。
解决方案:
新建一个RowBoundCapsule类,将原来的查询参数和limit、offset封装到一起,并采用如下的方式改写mapper文件:
<select id="selectByOwner" parameterType="int" resultMap="topicresultmap" resultSetType="FORWARD_ONLY"> select t.tid as tid, t.uid as tuid, t.content as content, t.commentcount as commentcount, t.pptime as pptime, u.uid as uid, u.email as email, u.nickname as nickname, u.login as login, u.pass as pass, u.pic as pic from topic as t LEFT JOIN user as u on t.uid = u.uid where t.uid = #{o} limit #{offset},#{limit} </select>
#{o}代表原来的参数。这样就可以把分页的任务交给数据库来完成了。
=====================
或者不要rowbounds了,直接传offset和pageSize到dao中,然后在sql后加limit #{offset},#{limit}
时间: 2024-12-26 13:44:05