• 多表连接


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

  • 相关阅读:
    [ZJOI2019]开关
    ABC245 Ex Product Modulo 2
    [SDOI2017]天才黑客
    ABC240G Teleporting Takahashi
    ABC240 Ex Sequence of Substrings
    ABC241H Card Deck Score
    mysql报错1055 only_full_group_by解决办法
    docker删除镜像Error response from daemon: conflict: unable to remove repository reference
    Docker服务启动报错:Job for docker.service failed because the control process exited with error
    bash: ifconfig: 未找到命令 解决方案
  • 原文地址:https://www.cnblogs.com/yjh1995/p/13893656.html
Copyright © 2020-2023  润新知