首页 > 其他分享 >8. 自定义映射resultMap

8. 自定义映射resultMap

时间:2023-06-06 09:56:22浏览次数:44  
标签:映射 自定义 did resultMap 查询 dept id 加载

在 Mybatis 中,resultType 和 resultMap 都用于定义查询结果的映射关系。它们的使用场景如下:

  1. resultType

resultType 用于指定返回结果的数据类型,通常用于返回简单类型的结果以及返回 vo 或 dto 等自定义类型的结果。例如:

<select id="findUserById" parameterType="int" resultType="com.example.User">
  select * from user where id = #{id}
</select>

这里 resultType 指定了查询结果将以 com.example.User 类型返回,Mybatis 会自动将查询结果映射到 User 对象中。resultType 适用于简单的查询操作,能够方便快捷地获取数据库表中的数据,并且使用起来比较简单。

  1. resultMap

resultMap 用于自定义查询结果的映射规则,通常用于处理复杂的查询结果,或者需要使用嵌套查询等复杂查询操作。例如:

<resultMap id="userResultMap" type="com.example.User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name" />
  <result property="email" column="user_email" />
  <association property="orders" javaType="list" resultMap="orderResultMap" />
</resultMap>

<resultMap id="orderResultMap" type="com.example.Order">
  <id property="id" column="order_id" />
  <result property="amount" column="order_amount" />
  <result property="createTime" column="create_time" />
</resultMap>

<select id="findUserById" parameterType="int" resultMap="userResultMap">
  select u.id as user_id, u.username as user_name, u.email as user_email,
  o.id as order_id, o.amount as order_amount, o.create_time
  from user u left join order o on u.id = o.user_id
  where u.id = #{id}
</select>

这里 resultMap 定义了 User 类型和 Order 类型的结果映射规则,Mybatis 会根据这些规则将复杂的查询结果映射到对应的 Java 类型中。对于复杂的查询操作,使用 resultMap 可以很好地处理查询结果中的各种细节,支持结果的拼接、嵌套等操作,使查询逻辑更加清晰。

1. resultMap 处理字段和属性的映射关系

若字段名和实体类中的属性名不一致,则可以通过 resultMap 设置自定义映射

<!--
    resultMap:设置自定义映射
    属性:
    id:表示自定义映射的唯一标识
    type:查询的数据要映射的实体类的类型
    子标签:
    id:设置主键的映射关系
    result:设置普通字段的映射关系
    association:设置多对一的映射关系
    collection:设置一对多的映射关系
    属性:
    property:设置映射关系中实体类中的属性名
    column:设置映射关系中表中的字段名
-->
<resultMap id="userMap" type="User">
    <id property="id" column="id"></id>
    <result property="userName" column="user_name"></result>
    <result property="password" column="password"></result>
    <result property="age" column="age"></result>
    <result property="sex" column="sex"></result>
</resultMap>
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultMap="userMap">
	<!--select * from t_user where username like '%${mohu}%'-->
select id,user_name,password,age,sex from t_user where user_name likeconcat('%',#{mohu},'%')
</select>

  • resultMap:设置自定义映射

  • 属性:

    • id:表示自定义映射的唯一标识
    • type:查询的数据要映射的实体类的类型
  • 子标签 :

    • id:设置主键的映射关系
    • result:设置普通字段的映射关系
    • association:设置多对一的映射关系
    • collection:设置一对多的映射关系
  • 属性 :

    • property:设置映射关系中实体类中的属性名
    • column:设置映射关系中表中的字段名

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合 Java 的规则(使用驼峰)此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系:

  1. 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
  2. 可以在 MyBatis 的核心配置文件中设置一个全局配置信息 mapUnderscoreToCamelCase,可

以在查询表中数据时,自动将_类型的字段名转换为驼峰

例如:字段名 user_name,设置了 mapUnderscoreToCamelCase,此时字段名就会转换为 userName

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

image

2. 多对一映射处理

2.1 级联方式处理映射关系

场景模拟: 查询员工信息以及员工所对应的部门信息

语法显示: (注意 column 和 property 的位置)

    <resultMap id="empAndDeptByEmpId" type="Emp">
       <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <result column="dept_id" property="dept.deptId"></result>
        <result column="dept_name" property="dept.deptName"></result>
    </resultMap>


    <select id="getEmpAndDeptById" resultMap="empAndDeptByEmpId">
        select t_emp.* , t_dept.*
	from t_emp left join t_dept on t_emp.dept_id = t_dept.dept_id where t_emp.emp_id = #{empId}
    </select>

2.2 使用 association 处理映射关系

    <resultMap id="empAndDeptByEmpIdTwo" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <association property="dept" javaType="Dept">
            <result column="dept_id" property="deptId"></result>
            <result column="dept_name" property="deptName"></result>
        </association>
    </resultMap>


    <select id="getEmpAndDeptById" resultMap="empAndDeptByEmpIdTwo">
        select t_emp.* , t_dept.*
	from t_emp left join t_dept on t_emp.dept_id = t_dept.dept_id where t_emp.emp_id = #{empId}
    </select>

  • association : 处理多对一的映射关系 (处理实体类型的属性)
  • property : 设置需处理映射关系的属性的属性名
  • JavaType : 设置要处理的属性的类型

3. 分步查询

① 查询员工信息

代码示例 :

    /**
     * 通过分步查询员工信息
     * @param empId
     * @return
     */
    Emp getEmpByStep(@Param("empId") Integer empId);

    <resultMap id="empDeptSteMap" type="Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <association property="dept"
                     select="com.north.mybatis.mapper.DeptMapper.getEmpDeptByStep"
                     column="dept_id"
                     ></association>
    </resultMap>

    	<!--
        select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
        column:将sql以及查询结果中的某个字段设置为分步查询的条件
	-->

    <select id="getEmpByStep" resultMap="empDeptSteMap">
        select * from t_emp where emp_id = #{empId}
    </select>

② 根据员工所对应的部门 id 查询部门信息

代码示例如下 :

    /**
     * 分步查询的第二步: 根据员工所对应的did查询部门信息
     * @param deptId
     * @return
     */
    Dept getEmpDeptByStep(@Param("deptId") Integer deptId);

        <select id="getEmpDeptByStep" resultType="Dept">
            select * from t_dept where dept_id  = #{deptId}
        </select>

3. 延迟加载

Mybatis 中的延迟加载指的是在查询主体对象时,只查询主体对象的信息,而对于关联的属性或集合对象,直到访问这些对象时才会进行查询操作,以达到减少查询次数、提高性能的目的。

延迟加载的作用是:

  1. 减少查询次数:当需要查询的数据量较大时,可以通过延迟加载避免一次性查询所有的数据,大大降低数据库的负载和查询时间,提高查询效率。
  2. 避免冗余数据:当主体对象包含多个关联属性或集合对象时,如果一次性加载所有数据,有可能会产生冗余的查询数据,而使用延迟加载可避免这种情况的出现,节省资源。
  3. 提升性能:当关联对象比较复杂时,一次性加载所有数据可能会显著降低程序的运行效率,使用延迟加载技术可以避免这种问题,并提高程序的运行速度。

延迟加载在 Mybatis 中的实现是通过动态代理实现的,Mybatis 在查询主体对象时,只返回代理对象,当第一次访问代理对象的相关属性时,会触发查询操作,从而实现延迟加载的效果。不过需要注意的是,Mybatis 中延迟加载的实现需要依赖于持久化框架和数据库的支持,如果底层不支持延迟加载,Mybatis 的延迟加载技术则无法实现,需要采取其他的手段进行基于性能的优化。

4. 一对多映射处理

4.1 collection

/**
* 根据部门id查新部门以及部门中的员工信息
* @param did
* @return
*/
Dept getDeptEmpByDid(@Param("did") int did);
<resultMap id="deptEmpMap" type="Dept">
    <id property="did" column="did"></id>
    <result property="dname" column="dname"></result>
    <!--
        ofType:设置collection标签所处理的集合属性中存储数据的类型
    -->
    <collection property="emps" ofType="Emp">
        <id property="eid" column="eid"></id>
        <result property="ename" column="ename"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
    </collection>
</resultMap>
<!--Dept getDeptEmpByDid(@Param("did") int did);-->
<select id="getDeptEmpByDid" resultMap="deptEmpMap">
    select dept.*,emp.* from t_dept dept left join t_emp emp on dept.did =emp.did where dept.did = #{did}
</select>

4.2、分步查询

① 查询部门信息

/**
* 分步查询部门和部门中的员工
* @param did
* @return
*/
Dept getDeptByStep(@Param("did") int did);
<resultMap id="deptEmpStep" type="Dept">
    <id property="did" column="did"></id>
    <result property="dname" column="dname"></result>
    <collection property="emps" fetchType="eager"select="com.atguigu.MyBatis.mapper.EmpMapper.getEmpListByDid" column="did">
    </collection>
</resultMap>
<!--Dept getDeptByStep(@Param("did") int did);-->
<select id="getDeptByStep" resultMap="deptEmpStep">
    select * from t_dept where did = #{did}
</select>

② 根据部门 id 查询部门中的所有员工

/**
* 根据部门id查询员工信息
* @param did
* @return
*/
List<Emp> getEmpListByDid(@Param("did") int did);
<!--List<Emp> getEmpListByDid(@Param("did") int did);-->
<select id="getEmpListByDid" resultType="Emp">
    select * from t_emp where did = #{did}
</select>

分步查询的优点:可以实现延迟加载

但是必须在核心配置文件中设置全局配置信息:

lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载

aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的 sql。此时可通过 association 和

collection 中的 fetchType 属性设置当前的分步查询是否使用延迟加载, fetchType="lazy(延迟加

载)|eager(立即加载)"

标签:映射,自定义,did,resultMap,查询,dept,id,加载
From: https://www.cnblogs.com/NorthPoet/p/17459703.html

相关文章

  • Vue自定义指令-让你的业务开发更简单
    1、使用场景在日常开发中,我们会将重复代码抽象为一个函数或者组件,然后在需要时调用或者引入。但是,对于某些功能,这种方法可能不够优雅或者不够灵活。例如,我们可能需要在DOM元素上添加一些自定义属性或者绑定一些事件,这些操作可能难以通过函数或组件来实现。这时,自定义指令就派上用......
  • qt 中的自定义pushbutton
       ......
  • WPF自学入门(四)WPF路由事件之自定义路由事件
      在上一篇博文中写到了内置路由事件,其实除了内置的路由事件,我们也可以进行自定义路由事件。接下来我们一起来看一下WPF中的自定义路由事件怎么进行创建吧。创建自定义路由事件分为3个步骤:1、声明并注册路由事件。2、利用CLR事件包装路由事件(封装路由事件)。3、创建可以激发路由......
  • 二、Spring Reactive Security自定义登录页
    添加配置类:@ConfigurationpublicclassMyReactiveSecurityConfig{@BeanpublicReactiveUserDetailsServicereactiveUserDetailsService(){UserDetailsuser=User.withUsername("user").password("12345")......
  • 为什么在stdio.h写自定义的宏不行?
    在自定义的头文件写可以: 这样写不行: ......
  • Asp.NetCore 自定义中间件
    这节演示一下自定义中间件,第一节我们讲到,中间件的处理流程就像一个俄罗斯套娃,那这种俄罗斯套娃型的流程内部是如何实现的呢,下面请看代码。    第一种写法是直接写在Configure方法中的,使用app.Use(委托)配合lambda表达式使用,适合很轻量级的中间件。app.Use(async(context,next......
  • wpf 自定义 RadioButton.
    <StyleTargetType="RadioButton"x:Key="nav"><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="RadioButton">......
  • pytorch 的 torchvision.datasets.ImageFolder 来自定义数据集
    importtorchvisionclassClassificationDataset(torchvision.datasets.ImageFolder): """ YOLOv5ClassificationDataset. Arguments root:Datasetpath """ def__init__(self,root): super().__init__(root=root)#调用了父类的......
  • 常用的开源自定义表单有哪几大优势特点?
    当前,办公已经进入流程化和自动化的阶段,要想跟随着社会发展,引用开源自定义表单工具可以使办公协作效率得到快速提升,它的灵活、便捷、易操作等特点,使得该表单工具深受当今职场的喜爱,是做好数据管理,提升办公表单制作效率和质量的得力助手。今天这篇文章就与大家一起分享常用的开源自......
  • 解绑自定义事件
    子组件中:  子组件:1)解绑一个自定义事件: 2)解绑多个自定义事件: 3)解绑所有的自定义事件: 销毁钩子也能解绑自定义事件: ......