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

  • 相关阅读:
    使用java检测网络连接状况
    利用java反射机制实现读取excel表格中的数据
    利用javaScript实现鼠标在文字上悬浮时弹出悬浮层
    29.满大街创业团队的年代,一不小心就被忽悠
    Android监测手指上下左右滑动屏幕
    Android 不规则封闭区域填充 手指秒变油漆桶
    2015华为暑期实习面试全过程
    如何将数据库中存的树转化为树形列表(以easyui的tree为例)
    tomcat6 高并发配置 与优化
    tomcat jvm优化
  • 原文地址:https://www.cnblogs.com/yjh1995/p/13893656.html
Copyright © 2011-2022 走看看