Mybatis一对多关联查询

2020-08-06  本文已影响0人  c_gentle

一、在实体类增加属性并添加set、get方法

  private List<GoodsDetail> goodsDetails;

二、编写xml中sql语句

<resultMap id="goodsMap" type="com.itlaoqi.mybatis.entity.Goods">
        <!-- 映射goods对象的主键到goods_id字段 -->
        <id column="goods_id" property="goodsId"></id>
        <!--
            collection的含义是,在
            select * from t_goods limit 0,1 得到结果后,对所有Goods对象遍历得到goods_id字段值,
            并代入到goodsDetail命名空间的findByGoodsId的SQL中执行查询,得到商品对应的GoodsDetail集合
            最后将这个集合赋值给goods.goodsDetails属性.
        -->
        <collection property="goodsDetails"//实体类中属性名
                    select="goodsDetail.findByGoodsId"
                    column="goods_id"/>
    </resultMap>
    <select id="selectOneToMany" resultMap="goodsMap">
      select * from t_goods limit 0,10
    </select>

另一个mapper文件

<mapper namespace="goodsDetail">
    <select id="findByGoodsId" parameterType="Integer" resultType="com.itlaoqi.mybatis.entity.GoodsDetail">
        select * from t_goods_detail where goods_id = #{value}
    </select>
</mapper>
上一篇 下一篇

猜你喜欢

热点阅读