Mybatis中实现多表查询

mybatis中实现多表查询方式

  1. 在业务层(service)中处理,对两张表分别编写单表查询语句,然后将结果合并。
  2. 使用mybatis中resultMap标签进行实现。

当多表查询时,类中包含另一个类的对象
这里主要使用第二种方法

一、resultMap属性

  • resultMap标签写在mapper.xml中,由程序员控制SQL查询结果与实体类的映射关系。
  • 默认MyBatis使用Auto Mapping特性
  • 使用resultMap 标签时,select标签不写resultType属性,而是使用resultMap属性引用resultMap标签

使用resultMap实现数据库表和表单映射关系
举例部门表和员工表
数据库字段(部门表)
在这里插入图片描述实体类
在这里插入图片描述DepartmentMapper.xml

 1  <mapper namespace="com.gm.springbootweb05restfulcrud.entities.Department">
       <resultMap type="Department" id="dept">
          <!-- 主键使用id标签配置映射关系-->
          <id column="id" property="id"/>
           <!-- 其他列使用result标签配置映射关系 -->
           <result  column="departmentName" property="departmentName"/>
       </resultMap>
 <!-- resultMap属性对应resultMap标签的id-->
       <select id="seleDept"  resultMap="dept">
           select * from department where id=#{id}
      </select>
  </mapper>

数据库字段(员工表)
在这里插入图片描述
实体类

在这里插入图片描述EmployeeMapper.xml

  • association装配一个对象时使用(包含在employee中的对象)
  • property 关联对象
  • select 通过哪个查询查询出这个对象的信息
  • column 把当前表的哪个列的值作为参数传递给另一个查询
    <resultMap id="emp" type="com.gm.springbootweb05restfulcrud.entities.Employee">
        <id property="id" column="id"/>
          <!--result如果对应可以省略-->
        <result property="lastName" column="lastName"/>
        <result property="email" column="email"/>
        <result property="gender" column="gender"/>
        <result property="birth" column="birth"/>
          <!--这里引用部门中根据id查询,由于员工表设计有问题,所以就把员工id和部门id对应了。select对应部门中查询方法,传入需要的值-->
        <association property="department" select="com.gm.springbootweb05restfulcrud.dao.DepartmentMapper.seleDept" column="id"/>

    </resultMap>

<select id="selEmp"  resultMap="emp">
    select * from employee
</select>

这样就实现了将department对象封装到employee中
更加详细:https://www.cnblogs.com/axu521/p/10109766.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值