Mybatis多对一 与一对多

本文介绍了MyBatis在处理一对多和多对一关系映射时的两种方法:结果集嵌套和查询嵌套。通过示例XML配置展示了如何在查询员工与部门、部门与员工的关系时,实现数据的联合查询和嵌套查询,从而获取完整的关联信息。
摘要由CSDN通过智能技术生成

查询数据的结果中存在多个对象中有同一个数据。类似于多个员工中含有同一个部门。

1.多对一--------SQL查询嵌套

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liuy.springMybatis.dao.EmpMapper">
    <resultMap id="emp_dept" type="Emp">
    <!--复杂属性之对象association   
    property属性名,
    column传入嵌套SQL参数---查询的列名
    javaType嵌套SQL返回类型,
    select嵌套SQL的ID-->
        <association property="dept" column="deptId" javaType="Dept" select="selectDeptById"/>
    </resultMap>
    <select id="selectAll" resultMap="emp_dept">
        select * from tbl_emp where name like concat('%','w','%')
    </select>
    <select id="selectDeptById" resultType="com.liuy.springMybatis.entity.Dept">
        select deptName from tbl_dept where id=#{deptId}
    </select>
</mapper>

只需要调用selectAll可得到员工以及员工部门信息。查询日志结果
在这里插入图片描述

2.多对一--------结果集嵌套

    <resultMap id="emp_dept" type="Emp">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
<!--  复杂属性之对象association   property复杂对象属性名,column---查询的列名,javaType嵌套SQL返回类型-->
        <association property="dept" column="deptId" javaType="Dept">
            <result property="deptName" column="deptName"/>
        </association>
    </resultMap>
    <select id="selectAll" resultMap="emp_dept">
        select tbl_emp.*,tbl_dept.deptName from tbl_emp,tbl_dept where tbl_emp.name like concat('%','w','%')  and tbl_emp.deptId=tbl_dept.id
    </select>

在这里插入图片描述
一对多:一个部门下有多个员工

1.一对多--------结果集嵌套

接收查询数据类Dept

@Data
public class Dept {
    int id;
    String deptName;
    String locAdd;
    List<Emp> emps;
}

Mapper.xml

    <resultMap id="Dept_emp" type="Dept">
        <result property="id" column="id"/>
        <result property="deptName" column="deptName"/>
        <collection property="emps" ofType="Emp">
            <result property="name" column="name"/>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="Dept_emp">
        select * from tbl_dept,tbl_emp where tbl_dept.id=#{id} and tbl_emp.deptId=tbl_dept.id
    </select>

查询结果 一个部门下 多个员工
在这里插入图片描述

2.一对多--------查询嵌套

<resultMap id="Dept_emp" type="Dept">
    <collection property="emps"  javaType="ArrayList" 
    ofType="Emp" select="selectEmpByDeptId" column="id"/>
</resultMap>
<select id="selectAll" resultMap="Dept_emp">
    select * from tbl_dept where tbl_dept.id=#{id}
</select>
<select id="selectEmpByDeptId" resultType="Emp">
    select * from tbl_emp where deptId=#{id}
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值