pageHelper 插件一对多查询分页问题

发布时间 2023-11-07 13:19:46作者: 爱喝茶的安迪

1.首先先确定我们需要返回的数据数据结构,这里我的贴出实体类(set/get方法自己生成)

public class BillInfoAndStudentInfoBean {
private String id;
private String billId;
private BigDecimal moneyTotal;
private List<ItemsBean> items;
}

2.然后我们在mapper.xml建立对应的关系,要实现分页正确我们需要建立两个 resultMap,一个用于子查询
注意,在主查询中的 collection里面要配置子查询sql查询id的方法名要对应,里面的 column 就是子查询你需要的查询条件,如果子查询需要多个条件column就这样写 column={id = billId,money = moneyTotal}
然后去子查询里面取值就好

主查询 resultMap
<resultMap id="BillInfoAndItemsInfo" type="com.lxd.domain.param.BillInfoAndStudentInfoBean">
<result column="id" property="id"></result>
<result column="billId" property="billId"></result>
<result column="moneyTotal" property="moneyTotal"></result>
<collection property="items" javaType="java.util.List" ofType="com.lxd.domain.param.ItemsBean" select="queryItemInfoById" column="billId">
</collection>
</resultMap>
子查询 resultMap
<resultMap id="ItemBeans" type="com.lxd.domain.param.ItemsBean">
<result column="item_name" property="item_name"></result>
<result column="item_price" property="item_price"></result>
<result column="is_sure" property="item_mandatory"></result>
</resultMap>

3.接下来可以开始写sql了

,注意这里的 方法名要和主查询 resultMap collection 里面 select 的方法名对应起来,这里传入的参数就是, collection 里面的 column

<单个参数>

<select id="queryItemInfoById" resultMap="ItemBeans">
SELECT ati.item_name,ati.item_price,ati.is_sure, atd.id FROM app_tuition_data atd
left JOIN app_tuition_item ati on atd.id=ati.tuition_id WHERE atd.id = #{billId}
</select>

<多个参数>

<select id="queryItemInfoById" resultMap="ItemBeans">
SELECT ati.item_name,ati.item_price,ati.is_sure, atd.id FROM app_tuition_data atd
left JOIN app_tuition_item ati on atd.id=ati.tuition_id WHERE atd.id = #{id} and #{money}
</select>

 

service 层和Mapper层和原来没有区别。该方法主要思路:先对主查询通过pagehelper插件做分页查询, 然后再做子查询。