MyBatis4-自定义映射resultMap、动态SQL

目录

自定义映射resultMap

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

多对一映射处理

一对多映射处理

动态SQL

if

where

trim

choose、when、otherwise

foreach

SQL片段


数据库:

实体类:

package com.qcby.pojo;

public class Emp {
    private Integer eid;

    private String empName;

    private Integer age;

    private String sex;

    private String email;

    public Emp() {
    }

    public Emp(Integer eid, String empName, Integer age, String sex, String email) {
        this.eid = eid;
        this.empName = empName;
        this.age = age;
        this.sex = sex;
        this.email = email;
    }

    public Integer getEid() {
        return eid;
    }

    public void setEid(Integer eid) {
        this.eid = eid;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "eid=" + eid +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}
package com.qcby.pojo;

public class Dept {
    private Integer did;

    private String deptName;

    public Dept() {
    }

    public Dept(Integer did, String deptName) {
        this.did = did;
        this.deptName = deptName;
    }

    public Integer getDid() {
        return did;
    }

    public void setDid(Integer did) {
        this.did = did;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "did=" + did +
                ", deptName='" + deptName + '\'' +
                '}';
    }
}

自定义映射resultMap

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

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性 名符合Java的规则(使用驼峰)

方式:

1.可以通过为字段起别名的方式,保证和实体类中的属性名保持一致


    /**
     * 查询所有的员工信息
     */
    List<Emp> getAllEmp();

    <select id="getAllEmp" resultType="com.qcby.pojo.Emp">
        select eid,emp_name empName,age,sex,email from t_emp
    </select>

2.可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰

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

    <!--设置mybatis的全局配置-->
    <settings>
        <!--将_自动映射为驼峰,emp_name:empName-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

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

    <!--
    resultMap:设置自定义映射
    id:表示自定义映射的唯一标识
    type:查询的数据要映射的实体类的类型
    子标签:
      id:设置主键的映射关系
      result:设置普通字段的映射关系
      association:设置多对一的映射关系
      collection:设置一对多的映射关系
    属性:
      property:设置映射关系中实体类中的属性名(type属性中的)
      column:设置映射关系中表中的字段名(sql语句中的)
    -->
    <resultMap id="empResultMap" type="com.qcby.pojo.Emp">
        <id property="eid" column="eid"></id>
        <id property="empName" column="emp_name"></id>
        <id property="age" column="age"></id>
        <id property="sex" column="sex"></id>
        <id property="email" column="email"></id>
    </resultMap>

    <select id="getAllEmp" resultMap="empResultMap">
        select * from t_emp
    </select>

多对一映射处理

查询员工信息以及员工所对应的部门信息

方式:

1.级联方式处理映射关系

    /**
     * 查询员工以及员工所对应的部门信息
     */
    Emp getEmpAndDept(@Param("eid") Integer eid);
    <resultMap id="empAndDeptResultMap" type="com.qcby.pojo.Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
        <result property="dept.did" column="did"></result>
        <result property="dept.deptName" column="dept_name"></result>
    </resultMap>
    <select id="getEmpAndDept" resultMap="empAndDeptResultMap">
        select * from t_emp left join t_dept on t_emp.did = t_dept.did
        where t_emp.eid = #{eid}
    </select>

2.使用association处理映射关系

     <!--
      association:处理多对一的映射关系
      property:需要处理多对的映射关系的属性名
      javaType:该属性的类型
     -->    
    <resultMap id="empAndDeptResultMap" type="com.qcby.pojo.Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
        <association property="dept" javaType="com.qcby.pojo.Dept">
            <id property="did" column="did"></id>
            <id property="deptName" column="dept_name"></id>
        </association>
    </resultMap>
    <select id="getEmpAndDept" resultMap="empAndDeptResultMap">
        select * from t_emp left join t_dept on t_emp.did = t_dept.did
        where t_emp.eid = #{eid}
    </select>

3.分步查询

(1)查询员工信息

(2)根据员工所对应的部门id查询部门信息

Emp:

    /**
     * 通过分步查询员工以及员工所对应的部门信息
     */
    //第一步:查询员工信息
    Emp getEmpAndDeptByStepOne(@Param("eid")Integer eid);
    <resultMap id="getEmpAndDeptByStepResultMap" type="com.qcby.pojo.Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
        <association property="dept"
                     select="com.qcby.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                     column="did">
        </association>
    </resultMap>
    <select id="getEmpAndDeptByStepOne" resultMap="getEmpAndDeptByStepResultMap">
        select * from  t_emp where eid = #{eid}
    </select>

Dept:

    //分步查询第二步:通过did查询员工所对应的部门
    Dept getEmpAndDeptByStepTwo(@Param("did")Integer did);

    <select id="getEmpAndDeptByStepTwo" resultType="com.qcby.pojo.Dept">
        select * from t_dept where did = #{did}
    </select>

一对多映射处理

方式:

1.collection

    /**
     * 获取部门以及部门中所有的员工信息
     */
    Dept getDeptAndEmp(@Param("did") Integer did);
    <!--
      collection:处理一对多的映射关系
      ofType:表示该属性所对应的集合中存储数据的类型
    -->
    <resultMap id="deptAndEmpResultMap" type="com.qcby.pojo.Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps" ofType="com.qcby.pojo.Emp">
            <id property="eid" column="eid"></id>
            <result property="empName" column="emp_name"></result>
            <result property="age" column="age"></result>
            <result property="sex" column="sex"></result>
            <result property="email" column="email"></result>
        </collection>
    </resultMap>
    <select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
        select * from t_dept left join t_emp on t_dept.did = t_emp.did
        where t_dept.did = #{did}
    </select>

2.分步查询

分步查询一般第一步使用resultMap,第二步使用resultType

Dept:

    /**
     * 分步查询部门以及部门中所有的员工信息
     */
    //分步查询第一步:查询部门信息
    Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
    <resultMap id="deptAndEmpByStepResultMap" type="com.qcby.pojo.Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="com.qcby.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="did">
        </collection>
    </resultMap>
    <select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepResultMap">
        select * from t_dept where did = #{did}
    </select>

Emp:

    //分步查询第二步:根据did查询员工信息
    List<Emp> getDeptAndEmpByStepTwo(@Param("did")Integer did);
    <select id="getDeptAndEmpByStepTwo" resultType="com.qcby.pojo.Emp">
        select * from  t_emp where did = #{did}
    </select>

分步查询

优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息

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

aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载 ,此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql

可通过association和 collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)"

    <!--设置mybatis的全局配置-->
    <settings>
        <!--将_自动映射为驼峰,emp_name:empName-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

 

动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题

if

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行

    /**
     * 多条件查询
     */
    List<Emp> getEmpByCondition(Emp emp);
   <select id="getEmpByCondition" resultType="com.qcby.pojo.Emp">
        select * from t_emp where 1 = 1
        <if test="empName != null and empName != ''">
            and emp_name = #{empName}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>
        <if test="sex != null and sex != ''">
            and sex = #{sex}
        </if>
        <if test="email != null and email != ''">
            and email = #{email}
        </if>
    </select>

where

where和if一般结合使用:

a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字

b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and或or去掉

注意:where标签不能去掉条件最后多余的and或or

    <select id="getEmpByCondition" resultType="com.qcby.pojo.Emp">
        select * from t_emp
        <where>
            <if test="empName != null and empName != ''">
                emp_name = #{empName}
            </if>
            <if test="age != null and age != ''">
                and age = #{age}
            </if>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="email != null and email != ''">
                and email = #{email}
            </if>
        </where>
    </select>

trim

trim用于去掉或添加标签中的内容

常用属性:

  • prefix:在trim标签中的内容的前面添加某些内容
  • prefixOverrides:在trim标签中的内容的前面去掉某些内容
  • suffix:在trim标签中的内容的后面添加某些内容
  • suffixOverrides:在trim标签中的内容的后面去掉某些内容
    <select id="getEmpByCondition" resultType="com.qcby.pojo.Emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and">
            <if test="empName != null and empName != ''">
                emp_name = #{empName} and
            </if>
            <if test="age != null and age != ''">
                age = #{age} and
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex} and
            </if>
            <if test="email != null and email != ''">
                email = #{email}
            </if>
        </trim>
    </select>

choose、when、otherwise

choose、when、otherwise相当于if...else if..else

    <select id="getEmpByCondition" resultType="com.qcby.pojo.Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName != null and empName != ''">
                    emp_name = #{empName}
                </when>
                <when test="age != null and age != ''">
                    age = #{age}
                </when>
                <when test="sex != null and sex != ''">
                    sex = #{sex}
                </when>
                <when test="email != null and email != ''">
                    email = #{email}
                </when>
                <otherwise>
                    did = 1
                </otherwise>
            </choose>
        </where>
    </select>

foreach

属性:

  • collection:设置要循环的数组或集合
  • item:表示集合或数组中的每一个数据
  • separator:设置循环体之间的分隔符
  • open:设置foreach标签中的内容的开始符
  • close:设置foreach标签中的内容的结束符
    /**
     * 通过数组批量删除
     */
    Integer deleteMoreByArray(@Param("eids") Integer[] eids);
    <delete id="deleteMoreByArray">
        delete from t_emp where eid in
        <foreach collection="eids" item="eid" separator="," open="(" close=")">
            #{eid}
        </foreach>
    </delete>
    <delete id="deleteMoreByArray">
        delete from t_emp where
        <foreach collection="eids" item="eid" separator="or">
            eid = #{eid}
        </foreach>
    </delete>
    /**
     * 批量插入
     */
    Integer insertMoreByList(@Param("emps") List<Emp> emps);
    <insert id="insertMoreByList">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.age},#{emp.email},null)
        </foreach>
    </insert>

SQL片段

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

    <sql id="empColumns">eid,emp_name,age,sex,email</sql>

    <select id="getEmpByCondition1" resultType="com.qcby.pojo.Emp">
        select <include refid="empColumns"></include> from t_emp
        <where>
            <choose>
                <when test="empName != null and empName != ''">
                    emp_name = #{empName}
                </when>
                <when test="age != null and age != ''">
                    age = #{age}
                </when>
                <when test="sex != null and sex != ''">
                    sex = #{sex}
                </when>
                <when test="email != null and email != ''">
                    email = #{email}
                </when>
                <otherwise>
                    did = 1
                </otherwise>
            </choose>
        </where>
    </select>
### MyBatis-Plus 中 resultMap 的使用方法及配置示例 #### 什么是 resultMap? `resultMap` 是 MyBatis 提供的一种强大的映射机制,用于定义数据库查询结果集与 Java 对象之间的复杂关系。它允许开发者手动指定列名和对象属性的对应关系,尤其适用于处理嵌套结构或多表联查的结果。 尽管 MyBatis-Plus 默认支持简单的 CRUD 操作并能自动生成 SQL 映射,但在某些场景下仍需借助 `resultMap` 来实现更复杂的业务需求[^1]。 --- #### 配置 resultMap 的基本语法 以下是 `resultMap` 的基础 XML 配置模板: ```xml <resultMap id="UserResultMap" type="com.example.entity.User"> <!-- 主键字段 --> <id property="userId" column="user_id"/> <!-- 普通字段 --> <result property="username" column="username"/> <result property="email" column="email"/> <!-- 嵌套关联 --> <association property="profile" javaType="com.example.entity.Profile"> <id property="profileId" column="profile_id"/> <result property="address" column="address"/> </association> <!-- 多对多关联 --> <collection property="roles" ofType="com.example.entity.Role"> <id property="roleId" column="role_id"/> <result property="name" column="role_name"/> </collection> </resultMap> ``` 上述代码展示了如何通过 `<resultMap>` 定义一个实体类及其关联的关系。其中: - `type` 表示目标 Java 实体类。 - `<id>` 和 `<result>` 分别表示主键字段和其他普通字段。 - `<association>` 用于一对一关联。 - `<collection>` 用于一对多或集合类型的关联。 --- #### 结合 MyBatis-Plus 使用 resultMap 的示例 假设有一个用户表 (`user`) 和其对应的个人资料表 (`profile`),两者之间存在外键关系。我们可以通过如下方式配置 `resultMap` 并执行查询操作。 ##### 数据库设计 | user (表) | profile (表) | |-------------------|--------------------| | user_id | profile_id | | username | address | | email | phone | ##### Mapper 文件配置 ```xml <mapper namespace="com.example.mapper.UserMapper"> <!-- 定义 resultMap --> <resultMap id="UserWithProfileResultMap" type="com.example.entity.User"> <id property="userId" column="user_id"/> <result property="username" column="username"/> <result property="email" column="email"/> <!-- 关联 Profile 表 --> <association property="profile" javaType="com.example.entity.Profile"> <id property="profileId" column="profile_id"/> <result property="address" column="address"/> <result property="phone" column="phone"/> </association> </resultMap> <!-- 查询语句 --> <select id="getUserById" resultMap="UserWithProfileResultMap"> SELECT u.user_id, u.username, u.email, p.profile_id, p.address, p.phone FROM user u LEFT JOIN profile p ON u.user_id = p.user_id WHERE u.user_id = #{userId} </select> </mapper> ``` ##### Service 层调用 在服务层中可以这样调用: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long userId) { return userMapper.getUserById(userId); } } ``` --- #### 注意事项 1. **优先级**:当同时存在 `@Results` 注解和 XML 配置时,XML 配置具有更高的优先级。 2. **性能优化**:对于简单的一一对应关系,推荐直接使用注解形式(如 `@TableField`),减少 XML 维护成本。 3. **逻辑删除兼容性**:如果启用了 MyBatis-Plus 的逻辑删除功能,则需要确保查询条件中加入过滤逻辑[^3]。 --- ### 总结 MyBatis-Plus 虽然简化了许多常见的 ORM 场景,但对于涉及复杂数据模型的情况,仍然依赖于原生 MyBatis 的 `resultMap` 功能来完成精确的数据映射。合理运用 `resultMap` 可以显著提升程序灵活性和可维护性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值