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

  • 相关阅读:
    bash:加减乘除(bc、let)
    shell配置文件
    HDU4624 Endless Spin 【最大最小反演】【期望DP】
    SPOJ10707 COT2
    HDU5977 Garden of Eden 【FMT】【树形DP】
    Codeforces1023E Down or Right 【贪心】
    Codeforces1023F Mobile Phone Network 【并查集】【最小生成树】
    UOJ272 [清华集训2016] 石家庄的工人阶级队伍比较坚强 【分治乘法】
    LOJ2721 [NOI2018] 屠龙勇士 【扩展中国剩余定理】
    UOJ268 [清华集训2016] 数据交互 【动态DP】【堆】【树链剖分】【线段树】
  • 原文地址:https://www.cnblogs.com/yjh1995/p/13893656.html
Copyright © 2011-2022 走看看