一对多查询
GoodsDetail.java
public class GoodsDetail{
private Integer gdId;
private Integer goodsId;
private String gdPicUrl;
private Integer gdOrder;
... setter和getter
}
Goods.java
public class Goods{
private Integer goodsId;
private String title;
private String subTitle;
private Float originalCost;
private Float currentPrice;
private Float discount;
private Integer isFreeDelivery;
private Integer categoryId;
private List<GoodsDetail> goodsDetails;
...setter getter
}
goods_detail.xml
<mapper namespace="goodsDetail">
<select id="selectByGoodsId" parameterType="Integer" resultType="com.imooc.mybatis.entity.GoodsDetail">
select * from t_goods_detail where goods_id=#{value}
</select>
</mapper>
goods.xml
<!--
resultMap可用于说明一对多或者多对一的映射逻辑
id是resultMap属性应用的标志
type指向One的实体(Goods)
-->
<resultMap id="rmGoods1" type="com.imooc.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中执行查询,
将得到的"商品详情"集合赋值给goodsDetails List对象
-->
<collection property="goodsDetails" select="goodsDetail.selectByGoodsId" column="goods_id"/>
</resultMap>
<select id="selectOneToMany" resultMap="rmGoods1">
select * from t_goods limit 0,10
</select>
List<Goods> list=session.selectList("goods.selectOneToMany");
多对一查询
GoodsDetail.java
public class GoodsDetail{
private Integer gdId;
private Integer goodsId;
private String gdPicUrl;
private Integer gdOrder;
private Goods goods;
... setter和getter
}
Goods.java
public class Goods{
private Integer goodsId;
private String title;
private String subTitle;
private Float originalCost;
private Float currentPrice;
private Float discount;
private Integer isFreeDelivery;
private Integer categoryId;
private List<GoodsDetail> goodsDetails;
...setter getter
}
goods_detail.xml
<mapper namespace="goodsDetail">
<resultMap id="rmGoodsDetail" type="com.imooc.mybatis.entity.GoodsDetail">
<id column="gd_id" property="gdId"/>
<association property="goods" select="goods.selectById" column="gd_id"/>
</resultMap>
<select id="selectManyToOne" resultMap="">
select * from t_goods_detail limit 0,1
</select>
</mapper>
goods.xml
<select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.Goods">
select * from t_goods where goods_id=#{value}
</select>
List<GoodsDetail> list=session.selectList("goodsDetail.selectManyToOne");
延迟加载 fetchType
- false 取消延迟加载
- true 支持延迟加载
在association标签
和collection标签
中可配置fetchType