zoukankan      html  css  js  c++  java
  • MyBatis 多表关联查询

    多表关联查询

    一对多  

    单条SQL实现。  


    //根据部门编号查询出部门和部门成员姓名
    public dept selectAll() thorws Excatipon;  //接口的抽象方法

    下面是对应接口的映射文件,关键代码

    <resultMap id="AllMapper" type="dept">

    <id column="deptNo" property="deptNo"></id>
    <result column="deptName" property="deptName"></result>
    <collection  property="emps" ofType="Emp">//collection用于集合对象,property对应实体中的集合变量名, ofType元素类型为Emp,因为集合中的数据类型都是Emp的。
        <id column="empNo" property="empNo"></id>
    <result column="empName" property="empName"></result>
    </collection>

    </resultMap>

    <select id="selectAll"  resultMap=”AllMapper”>  //id对应接口中的方法,resultMap对应上面resultMap的id中的内容。

    SELECT * FROM dept,emp WHERE dept.deptNo=emp.deptNo AND dept.deptNo=#{占位符}

    </select>

     测试类中的代码:

    一对多多条SQL实现。

    //根据部门编号查询出部门和部门成员姓名

    public dept selectTwo() thorws Excaption;//接口中的方法

    数据库测试

    映射文件代码:

    测试类运行代码:

    多对一关联查询

    接口代码:

    映射文件代码:  其实就是多的一方对一的一方,  sql语句也就是换了个条件, 要灵活运用

    测试类代码:

    多对多关联查询

     select student.sid,sname,teacher.tid,tname
            from student,teacher_student,teacher
            where student.sid=teacher_student.sid
             and  teacher.tid=teacher_student.tid
             and  teacher.tid=#{tid}

     其实多对多除了SQL语句和上面不一样其实实现思路都是一样的。可以灵活运用。

    自关联查询

    自关联查询,就是自己可以称多的一方,自己也可以称单的一方。

    按三级分类案例来说,自己有自己的父类,自己也可以有自己的子类

    表中有三列,一个是分类编号, 一个是分类名称,一个是父类分类编号,

    SQL语句  select * from  tree表 where  pid=上次查询出的数据的cid

  • 相关阅读:
    C++引用小结
    C++关于const的使用以及理解
    python购物车程序的简单程序优化版
    C++文件操作
    python购物车简单小程序
    python学习DAY3(列表)
    C++重载双目运算符(2)(对象与数之间)
    C++重载双目运算符(1)(对象与对象之间)
    C++重载单目运算符
    Elasticsearch 添加数据
  • 原文地址:https://www.cnblogs.com/java-263/p/9934125.html
Copyright © 2011-2022 走看看