resultMap自定义映射(一对多)

collection:处理一对多和多对多的关系
  1) POJO中的属性可能会是一个集合对象,我们可以使用联合查询,并以级联属性的方式封装对象.使用collection标签定义对象的封装规则

 

复制代码
public class Dept {
    private Integer did;
    private String dname;
    private List<Emp> emps;
    // 省略 get/set方法
}
public class Emp {
    private Integer eid;
    private String ename;
    private Integer age;
    private String sex;
    private Dept dept;
    // 省略 get/set方法
}
复制代码

查询某一部门下的所有员工信息:

复制代码
    <resultMap type="Dept" id="deptMap">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <!-- 
            <collection>:处理一对多和多对多的关系
            ofType:指集合中的类型,不需要指定javaType
         -->
        <collection property="emps" ofType="Emp">
            <id column="eid" property="eid"/>
            <result column="ename" property="ename"/>
            <result column="age" property="age"/>
            <result column="sex" property="sex"/>
        </collection>
    </resultMap>
    
    <!-- Dept getDeptEmpsByDid(String did); -->
    <select id="getDeptEmpsByDid" resultMap="deptMap">
        select d.did,d.dname,e.eid,e.ename,e.age,e.sex from dept d left join emp e on d.did = e.did where d.did = #{did}
    </select>
复制代码

   2)collection 分步查询
  实际的开发中,对于每个实体类都应该有具体的增删改查方法,也就是DAO层, 因此对于查询部门信息并且将对应的所有的员工信息也查询出来的需求,就可以通过分步的方式完成查询。
    ① 先通过部门的id查询部门信息
    ② 再通过部门id作为员工的外键查询对应的信息.

复制代码
   
    <!-- List<Emp> getEmpListByDid(String did); -->
    <select id="getEmpListByDid" resultType="Emp">
        select eid,ename,age,sex from emp where did = #{did}
    </select>
    
    <resultMap type="Dept" id="deptMapStep">
        <id column="did" property="did"/>
        <result column="dname" property="dname"/>
        <collection property="emps" select="com.atguigu.mapper.EmpDeptMapper.getEmpListByDid" column="{did=did}" fetchType="eager"></collection>
    </resultMap>
    
    <!-- Dept getOnlyDeptByDid(String did); -->
    <select id="getOnlyDeptByDid" resultMap="deptMapStep">
        select did,dname from dept where did = #{did}
    </select>
复制代码

 column="{did=did}中如果有多个参数,则以map键值对的方式,但要注意在后面的sql语句中要对应好键的名称。

 

扩展: association 或 collection的 fetchType属性
  1) 在<association> 和<collection>标签中都可以设置fetchType,指定本次查询是否要使用延迟加载。默认为 fetchType= ”lazy” ,如果本次的查询不想使用延迟加载,则可设置为fetchType=”eager”.
  2) fetchType可以灵活的设置查询是否需要使用延迟加载,而不需要因为某个查询不想使用延迟加载将全局的延迟加载设置关闭.

 

posted @   kkzhang  阅读(1860)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示