从零开始系列——1对多关系查询
1.OneToMany关联查询
举例:淘宝上的物品都会使用多张图片来进行描述,也就是一个物品对应多张图片
One : 物品
Many:物品图片
OneToMany的实质:通过物品来找到对应的物品图片
<?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="goodsDetail">
<select id="selectByGoodsId" parameterType="Integer" resultType="com.lx.entity.GoodsDetail">
select * from t_goods_detail where goods_id = #{value}
</select>
</mapper>
public class Goods {
private Integer goodsId; // 商品编号
private String title; // 标题
private String subTitle; // 副标题
private Float originalCost; // 原始价格
private Float currentPrice; // 当前价格
private Float discount; // 折扣率
private Integer isFreeDelivery; // 是否包邮 1-包邮 0不包邮
private Integer categoryId; // 分类编号
private List<GoodsDetail> goodsDetailLists; // 一个Goods对象下可以有多个GoodsDetail对象 一对多
}
<?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">
<!-- namespace:命名空间 用来区分sql id-->
<mapper namespace="goods">
<resultMap id="rmGoods1" type="com.lx.entity.Goods">
<id column="goods_id" property="goodsId"></id>
<collection property="goodsDetailLists" select="goodsDetail.selectByGoodsId" column="goods_id"/>
</resultMap>
<select id="selectOneToMany" resultMap="rmGoods1">
select * from t_goods limit 0,2
</select>
</mapper>
<collection>:描述Goods中的goodsDetailLists属性数据从何而来
collection的含义是在select * from t_goods limit 0,2得到结果后,对所有Goods对象遍历得到goods_id字段值
并代入到goodsDetail命名空间下的selectByGoodsId的SQL语句中查询
将得到的商品详情集合赋值到goodsDetails list集合中
实际调用goods.selectOneToMany即可,返回Goods对象,而我们需要只是Goods对象中的goodsDetailList属性,里面封装了某个物品对应的所有图片信息