1 对多关联查询
创建t_goods_detail.xml文件
<?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.mybatis.entity.GoodsDetail">
select * from t_goods_detail where goods_Id = #{value}
</select>
</mapper>
在goods.xml中添加一个select标签
<!-- 在对象关联的情况下是通过resultMap这个标签来实现的
resultMap可用于说明一对多或者多对一的映射逻辑
id是resultMap属性引用的标志
type是指向One的实体(Goods)
-->
<resultMap id="rmGoods1" type="com.mybatis.entity.Goods">
<!-- 映射goods对象的主键到goods_Id字段 -->
<id column="goods_Id" property="goodsId"/>
<!--
collection 的含义是,在
select * from t_goods limit 0.1 得到结果后,对所有Goods对象遍历得到goods_id字段值,
并代入到goodsDetail命名空间的findByGoodsId的SQL中的执行查询。
将得到的“商品详情”集合赋值给goodsDetails list对象
-->
<collection property="goodsDetail" select="goodsDetail.selectByGoodsId" column="goods_id"/>
</resultMap>
<select id="selectOneToMany" resultMap="rmGoods1">
select * from t_goods limit 0, 10
</select>
config文件中增加mapper映射
在Goods类中添加一个属性 private List goodsDetail;,并创建get、set方法
测试
@Test
/**
* 一对多
*
*/
public void testOneToMany() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
List<Goods> goods = session.selectList("goods.selectOneToMany");
for(Goods g :goods){
System.out.println(g.getTitle() + ":" +g.getGoodsDetails().size());
}
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}
2 多对一关联查询
在goods_detail.xml中添加select标签
<resultMap id="rmgoodsDetail" type="com.mybatis.entity.GoodsDetail">
<id column="gd_id" property="gdId"/>
<result column="goods_Id" property="goodsId"/>
<association property="goods" select="goods.selectById" column="goods_Id"/>
</resultMap>
<select id="selectManyToOne" resultMap="rmgoodsDetail">
select * from t_goods_detail limit 0,4
</select>
在GoodsDetail中添加Goods对象,和get、set方法
测试
@Test
/**
* 多对一
*
*/
public void testManyToOne() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
List<GoodsDetail> goods = session.selectList("goodsDetail.selectManyToOne");
for(GoodsDetail gd :goods){
System.out.println(gd.getGdPicUrl() + ":" +gd.getGoods().getTitle());
}
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}