Mybatis的一对多和多对一(association和collection)

Mybatis的一对多和多对一

MyBatis 创建时的一个思想是:数据库不可能永远是你所想或所需的那个样子。 我们希望每个数据库都具备良好的第三范式或 BCNF 范式,可惜它们并不都是那样。 如果能有一种数据库映射模式,完美适配所有的应用程序,那就太好了,但可惜也没有。 而 ResultMap 就是 MyBatis 对这个问题的答案。
比如在user这个类里面有一个book类的对象,表示学生借的书,由于一个学生可以借多本书,所以学生与书的关系就是多对一的关系,而学生表中只有的id,此时如何从数据库取出book的对象,此时我们就需要用到association

resultMap 元素有很多子元素和一个值得深入探讨的结构。 下面是resultMap 元素的概念视图。
结果映射(resultMap)
association – 一个复杂类型的关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
collection – 一个复杂类型的集合
嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用

一对多:
第一种方式:子查询

  <select id="getborrow" resultMap="Bookuser">
        select bookid from borrow
    </select>
    <resultMap id="BookStudent" type="pojo.Borrow">
          <association property="book" column="bookid" javaType="pojo.Book" select="getbookbyid"></association>
    </resultMap>
    <select id="getbookbyid" resultType="pojo.Book">
        select * from book where id=#{id}
        <!--这里的#{id}中除了id可以随便写什么,他是通过第一个子查询传的参数进来的,因为就查询结果就一个-->
    </select>

第二种方式:
按结果嵌套处理(联表查询)

<select id="getborrow" resultMap="Bookuser">
    select b.* from book b,borrow bo where b.id=bo.bookid
</select>
<resultMap id="BookStudent" type="borrow">
    <association property="book" javaType="Book">
        <result property="id" column="id"></result>
        <result property="bname" column="bname"></result>
        <result property="price" column="price"></result>
        <result property="author" column="author"></result>
        <result property="content" column="content"></result>
    </association>

</resultMap>

多对一:
在这里插入图片描述

    <select id="getuserbooks" resultMap="users">
    <!--这一条语句可以查询出所有你需要的结果,即上表的id,number,name,password,ismanager,books然后用collection收集-->
    select u.id,u.number,u.name,u.password,u.ismanager,b.id bid,b.* from user u join borrow      bo on u.id=bo.borrowid join book  b on b.id=bo.bookid where u.id=#{id}
</select>
    <resultMap id="users" type="user">
        <result property="id" column="id"></result>
        <result property="number" column="number"></result>
        <result property="name" column="name"></result>
        <result property="password" column="password"></result>
        <result property="ismanager" column="ismanager"></result>
        <collection property="books" ofType="book">
            <result property="id" column="bid"></result>
            <result property="bname" column="bname"></result>
            <result property="price" column="price"></result>
            <result property="author" column="author"></result>
            <result property="content" column="content"></result>
        </collection>
    </resultMap>

mybatis1

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值