zoukankan      html  css  js  c++  java
  • 多表连接

    参考   https://www.jianshu.com/p/018c0f083501

    association标签

    association标签:一对一 和 多对一

    • 作用:将关联查询信息映射到一个pojo类中。

    • 场合:为了方便获取关联信息可以使用association将关联信息映射为pojo,比如:查询学生和card的关系

    两种方式:

    • 只写一个映射文件StudentMapper.xml(CardMapper不能在其他映射文件中复用)

    <mapper namespace="mybatis_test.StudentMapper">
        <resultMap id="studentMap" type="mybatis_test.Student">
            <id column="id" property="id"/>
            <result column="sname" property="name"/>
            <association property="card" javaType="mybatis_test.Card">
                <id column="cid" property="id"/>
                <result column="cnum" property="num"/>
            </association>
        </resultMap>
        <select id="findById" resultMap="studentMap">
            select * from students s,cards c where s.scid=c.cid and s.id=#{id}
        </select>
    </mapper>
    • 写两个映射文件StudentMapper.xml和CardMapper(能在其他映射文件中复用)

    <!--CardMapper.xml-->
    <mapper namespace="mybatis_test.CardMapper">
        <resultMap id="cardMap" type="mybatis_test.Card">
            <id column="cid" property="id"/>
            <result column="cnum" property="num"/>
        </resultMap>
    </mapper>
    
    <!--StudentMapper.xml-->
    <mapper namespace="mybatis_test.StudentMapper">
        <resultMap id="studentMap" type="mybatis_test.Student">
            <id column="id" property="id"/>
            <result column="sname" property="name"/>
            <association property="card" resultMap="cardMap"/>
        </resultMap>
    </mapper>

    collection标签

    collection标签:一对多

    • 作用:将关联查询信息映射到一个list集合中。

    • 场合:为了方便获取关联信息可以使用collection将关联信息映射到list集合中,比如:查询一个人有多个手机

    • ofType属性一定不能少,collection 装的元素类型是啥ofType的值就是啥

    两种方式:

    • 只写一个映射文件UserMapper.xml(PhoneMapper不能在其他映射文件中复用)

    <mapper namespace="mybatis_test.UserMapper">
        <resultMap id="userMap" type="mybatis_test.User">
            <id column="uid" property="id"/>
            <result column="uname" property="name"/>
            <collection property="phones" ofType="mybatis_test.Phone" >
                <result column="pname" property="name"/>
            </collection>
        </resultMap>
        <select id="find" resultMap="userMap">
            select u.uid,u.uname,p.pname from user u,phone p where u.uid=p.u_pid and u.uid=#{id};
        </select>
    </mapper>
    • 写两个映射文件UserMapper.xml和PhoneMapper(能在其他映射文件中复用)

      ...

    由于SQL语句全是由我们自己写,如果我们返回的数据类型在当前的实体中是不够封装的话,那么我们只要再关联对应的映射属性就行了

  • 相关阅读:
    oracle热备份与冷备份的对比
    oracle数据库备份
    shell 去除空行
    已有实例 Oracle 下新增实例(2)通过dbca克隆实例
    oracle启动,提示“LRM-00109: could not open parameter file”
    linux——使用fidsk对linux硬盘进行操作【转】
    前端——知识点
    hdu 3996 Gold Mine 最大权闭合子图
    hdu 3917 Road constructions 最大权闭合子图
    poj 2987 Firing 最大权闭合子图
  • 原文地址:https://www.cnblogs.com/yjh1995/p/13893656.html
Copyright © 2011-2022 走看看