问题:在写mybatis一对多的时候用到了Pagehelper进行分页,然后发现确实能分页,但是展示的条数不对,后来研究了发现原来Pagehelper插件在一对多查询的时候默认的是对多的一方进行的分页,不是一的一方。
解决:目前我的解决方式是用子查询,这样能够达到我想要的效果,不过会出现N+1次查询,但是我目前没有找到更好的解决方法,有的朋友可以评论分享一下。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.lmj.order.mapper.OrderMainMapper">
<resultMap id="BaseResultMap" type="com.lmj.order.pojo.OrderMain">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="uid" property="uid" jdbcType="BIGINT"/>
<result column="del_flag" property="delFlag" jdbcType="TINYINT"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
<collection property="orderMainOrders" javaType="list"
ofType="com.lmj.order.pojo.OrderMainOrder" select="getOrderMainOrder"
column="{orderMainId=id}">
<result property="id" column="oId" jdbcType="BIGINT"/>
<result property="orderMainId" column="order_main_id" jdbcType="BIGINT"/>
<result property="orderId" column="order_id" jdbcType="BIGINT"/>
</collection>
</resultMap>
<select id="getOrderMain" resultMap="BaseResultMap">
SELECT * from order_main a WHERE a.del_flag = 0 and a.uid = #{uid}
</select>
<select id="getOrderMainOrder" parameterType="map"
resultType="map">
select b.id as oId,b.order_main_id,b.order_id
from order_main_order b
where b.order_main_id = #{orderMainId}
</select>
</mapper>
order_main表是一的一方,order_main_order是多的一方,然后我把多的一方作为子查询,对一的一方进行分页,就发现分页条数正确了。
这里要注意的就是几个点是否对应:
首先是查询方法名称一致。
然后就是使他们相关联的条件,order_main_order表中的orderMainId是order_main表中的id。这个样子就是使他们关联起来了。其实就是一个子查询。