MyBatis一对多、多对一关系

目录

简介

1、搭建MyBatis工程

2、创建表

3、创建实体类

员工(Emp.java)

部门(Dep.java)

4、创建实体映射文件

员工(EmpMapper.xml)

部门(DepMapper.xml)

5、测试代码

查询员工列表,第一种方式

查询员工列表,第二种方式

查询部门列表


简介

在实际的业务场景中,会碰到实体间的各种关联关系:一对多、多对一、多对多,如:员工和部门。MyBatis是如何处理这些关系的呢?

在MyBatis中,一对多使用 association 标签处理、多对一使用 collection 标签处理,具体实现步骤如下:

1、搭建MyBatis工程

参考《搭建Mybatis工程》

2、创建表

-- 员工表
DROP TABLE IF EXISTS emp;
CREATE TABLE emp (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    emp_name varchar(100) NOT NULL COMMENT '员工名称',
    dep_id int(11) NOT NULL COMMENT '部门ID',
    PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='员工表';

-- 部门表
DROP TABLE IF EXISTS dep;
CREATE TABLE dep (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    dep_name varchar(100) NOT NULL COMMENT '部门名称',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='部门表';

3、创建实体类

员工(Emp.java)

/**
 * 员工
 *
 * @author WangZonghuan
 * @date 2025/11/26 15:31
 */
public class Emp {
    /** ID */
    private int id;

    /** 员工名称 */
    private String empName;

    /** 部门ID */
    private int depId;

    /** 部门 */
    private Dep dep;
}

部门(Dep.java)

/**
 * 部门
 *
 * @author WangZonghuan
 * @date 2025/11/26 15:30
 */
public class Dep {
    /** ID */
    private int id;

    /** 部门名称 */
    private String depName;

    /** 员工 */
    private List<Emp> emps;
}

4、创建实体映射文件

员工(EmpMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.mybatis.mapper.EmpMapper">

    <resultMap id="queryEmpListResultMap" type="Emp">
        <id column="id" property="id"/>
        <result column="emp_name" property="empName"/>
        <result column="dep_id" property="depId"/>
        <association property="dep" column="dep_id">
            <id column="id" property="id"/>
            <result column="dep_name" property="depName"/>
        </association>
    </resultMap>

    <select id="queryEmpList" parameterType="Map" resultMap="queryEmpListResultMap">
        select * from emp
        left join dep on dep.id = emp.dep_id
        where emp_name like "%"#{empName}"%"
    </select>

    <resultMap id="queryEmpList2ResultMap" type="Emp">
        <id column="id" property="id"/>
        <result column="emp_name" property="empName"/>
        <result column="dep_id" property="depId"/>
        <association property="dep" column="dep_id" select="org.mybatis.mapper.DepMapper.getDep">
            <id column="id" property="id"/>
            <result column="dep_name" property="depName"/>
        </association>
    </resultMap>

    <select id="queryEmpList2" parameterType="Map" resultMap="queryEmpList2ResultMap">
        select * from emp where emp_name like "%"#{empName}"%"
    </select>

    <select id="getEmpList" parameterType="Int" resultType="Emp">
        select * from emp where emp.dep_id = #{depId}
    </select>
</mapper>

部门(DepMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.mybatis.mapper.DepMapper">

    <select id="getDep" parameterType="Int" resultType="Dep">
        select * from dep where id = #{id}
    </select>

    <resultMap id="queryDepListResultMap" type="Dep">
        <id column="id" property="id"/>
        <result column="dep_name" property="depName"/>
        <collection fetchType="eager" property="emps" ofType="Emp" column="id"
                    select="org.mybatis.mapper.EmpMapper.getEmpList">
            <id column="id" property="id"/>
            <result column="emp_name" property="empName"/>
        </collection>
    </resultMap>

    <select id="queryDepList" resultMap="queryDepListResultMap">
        select * from dep
    </select>
</mapper>

5、测试代码

查询员工列表,第一种方式

@Test
public void queryEmpList(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    Map<String, Object> params = new HashMap<>();
    params.put("empName", "王");

    List<Emp> list = empMapper.queryEmpList(params);
    list.forEach(v -> System.out.println(v.toString()));
}

执行结果:

查询员工列表,第二种方式

@Test
public void queryEmpList2(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    Map<String, Object> params = new HashMap<>();
    params.put("empName", "王");

    List<Emp> list = empMapper.queryEmpList2(params);
    list.forEach(v -> System.out.println(v.getEmpName() + "-" + v.getDep().getDepName()));
}

执行结果:

查询部门列表

@Test
public void queryDepList(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    DepMapper depMapper = sqlSession.getMapper(DepMapper.class);

    List<Dep> list = depMapper.queryDepList();
    list.forEach(v -> System.out.println(v.getDepName() + "-" + v.getEmps().size()));
}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值