MyBatis嵌套查询和嵌套结果区别以及一对一、一对多、多对多的映射实现

MyBatis嵌套查询和嵌套结果区别以及一对一、一对多、多对多的映射实现

嵌套查询和嵌套结果的区别
嵌套查询
  • 关联的嵌套查询显示得到一个结果集,然后根据这个结果集的每一条记录进行关联查询。

  • 内部就一个association标签, 现查询的结果集返回条数为N, 那么关联查询语句将会被执行N次,加上自身返回结果集查询1次,共需要访问数据库N+ 1次。如果N此较大的话,这样的数据库访问消耗是非常大的!

  • 嵌套语句的查询会导致数据库访问次数不定,进而有可能影响到性能。

嵌套结果
  • 即对于一对多,多对多,多对一的情况的查询,Mybatis通过联合查询,将结果从数据库内一-次性查出来,然后根据其一对一,一对多,多对多的关系和ResultMap中的配置,进行结果的转换。
一对一、一对多、多对多

● 一对一:在任意一方引入对方主键作为外键;

● 一对多:在“多”的一方,添加“一”的一方的主键作为外键;

● 多对多:产生中间关系表,引入两张表的主键作为外键,两个主键成为联合主键或使用新的字段作为主键。

● property:指定映射到的实体类对象属性,与表字段一一对应;

● column:指定表中对应的字段;

映射:一对一
<!-- 地址映射关系 -->
<resultMap id="addressMap" type= "com.learn.bean.Address">
	<id property="id" column=" address_ id"></id>
	<result property= "city" column= "city"></result>
</ resultMap>
<!-- 学生映射关系 -->

<resultMap id= " studentMap" type=" com.learn.bean.Student">
	<id property="id" column="id"/>
	<result property= "name" column= "name" />
	<association property="address" resultMap="addressMap"/>
</ resultMap>

<select id="findStudentWithAddressById" resultMap="studentMap">
    select a.id,a.name,b.id as address_ id,b. city
    from t_ student a
    left join t_ address b
    on a.address_ id = b.id
    where a.id = #{id}
</select>
映射:一对多
<resultMap id=" courseMap" type= "com.learn.bean.Course">
    <id property="id" column="c_ _id"></id>
    <result property= "name" column= "C_ name"></ result>
</resultMap>

<resultMap id= "teacherMap" type= " com.learn.bean.Teacher">
    <id property="id" column="t. _id"></id>
    <result property= ”name" column="t_ name"></result>
    <collection property=" courses" resultMap=" courseMap"></collection>
</resultMap>

<select id="findTeacherWithCourseById" resultMap= "teacherMap">
select a.t_ id,a.t_ name,b.c_ id,b. C_ name
        from t_ teacher a
        left join t_ course b
        on a.t_id = b.c . teacher id
        where a.t_id = #{id}
</select>


映射:多对多
<!-- 一个订单包含多个商品,一个商品属于多个订单 -->
<resultMap type="com.learn.bean.Orders" id="OrdersWithPorductResult2">
    <id property="id" column="id" />
    <result property="number" column="number" />
    <!-- 多对多关联映射:collection -->
    <collection property="productList" ofType="Product">
        <id property="id" column="pid" />
        <result property="name" column="name" />
        <result property="price" column="price" />
    </collection>
</resultMap>

<!-- 多对多嵌套结果查询:查询某订单及其关联的商品详情 -->
<select id="findOrdersWithPorduct2" parameterType="Integer" 
         resultMap="OrdersWithPorductResult2">
    select o.*,p.id as pid,p.name,p.price
    from tb_orders o,tb_product p,tb_ordersitem  oi
    WHERE oi.orders_id=o.id 
    and oi.product_id=p.id 
    and o.id=#{id}
</select>
小结

个人学习记录一下下!!

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值