20211025-20211031

本文介绍了如何在MyBatis中处理多对多关联查询,展示了一个示例,其中`resultMap`定义了一个包含嵌套`list`的结果集。查询时通过LEFT JOIN将Department和Employee表联查,结果集中每个Department对象包含一个Employee的`list`集合。同时,讨论了解决字段重名问题的方法,如避免使用*通配符,使用别名等。
摘要由CSDN通过智能技术生成

mybatis 多对多 返回list结果集,里面再嵌套list

<resultMap type="com.backendmanager.bean.Department" id="findAll">
    <id property="id" column="id" />
    <result property="departmentName" column="departmentName" />
    <collection property="employees" javaType="list"
        ofType="com.backendmanager.bean.Employee">
        <!-- 一对多出现的问题: 当数据库表中,主表的主键id和明细表的 ... 当表中的字段名相同时怎么办?多表联查? 注意:Mybatis中做多表联查的时候,不管是 
            一对一、一对多、一对多对多:多对多: 都不能有字段重名的情况:不管是主键还是普通字段。 一旦字段重名的话,就会造成数据少自动赋值,或者覆盖,甚至重复赋值! 
            规避和解决此类问题的方法: 1.尽量不要表间重名,mybatis里处理起来很麻烦!id和普通字段都是。 但是在表多的时候,很难不会出现字段重名的情况。主键id最容易重名! 
            那么就要用以下的办法了! 2.在mybatis中写原生SQL进行查询的时候,查的字段尽可能的少,这 也影响速率,强烈禁止使用*,用多少查多少!这样也能及时发现字段重 
            名的情况! 3.最后如果真的需要查出重名的字段,并且修改数据库字段名造成的更改 过大,这里推荐的方式是给字段取别名,在写resultMap映射的时候,其 
            中的column属性就填写SQL语句中查出字段取的别名,这样就能解决重复 问题了! -->
        <id property="id" column="eid" />
        <result property="lastName" column="lastname" />
        <result property="email" column="email" />
        <result property="gender" column="gender" />
        <result property="dId" column="did" />
    </collection>


</resultMap>
    <select id="findAll" resultMap="findAll">
        select t1.id,t1.departmentName,
        t2.id as eid,t2.lastname,t2.email,t2.gender,t2.did
        from Department t1 left join Employee t2 on t1.id=t2.did
        
    </select>

package com.backendmanager.bean;

import java.io.Serializable;
import java.util.List;

public class Department implements Serializable{
    private Integer id;
    private String departmentName;
    private List<Employee> employees;
    public Department() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Department(Integer id, String departmentName) {
        super();
        this.id = id;
        this.departmentName = departmentName;
    }
    @Override
    public String toString() {
        return "Department [id=" + id + ", departmentName=" + departmentName + "]";
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
    public List<Employee> getEmployees() {
        return employees;
    }
    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

}

Mybatis一对多关联查询,返回结果集list中嵌套list实例(collection实现)_守得云开见月明-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值