飞道的博客

Mybatis 的中高级特性使用

408人阅读  评论(0)

简介:

MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。

SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):

关于每个顶级元素 具体属性的详解,请移步官网: mybatis – MyBatis 3 | XML 映射器

本文只是针对新手开发中常见的几个问题,如何处理进行讲解:

1、自定义映射resultMap

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

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

官方介绍中说,resultMap属性是对 对外部 resultMap 的命名引用。结果映射是 MyBatis 最强大的特性,如果你对其理解透彻,许多复杂的映射问题都能迎刃而解。 resultType 和 resultMap 之间只能同时使用一个

resultMap 是Select标签中一个重要的属性之一:如下图


  
  1. <select
  2. id= "selectPerson"
  3. parameterType= "int"
  4. parameterMap= "deprecated"
  5. resultType= "hashmap"
  6. resultMap= "personResultMap"
  7. flushCache= "false"
  8. useCache= "true"
  9. timeout= "10"
  10. fetchSize= "256"
  11. statementType= "PREPARED"
  12. resultSetType= "FORWARD_ONLY">

之前你已经见过简单映射语句的示例,它们没有显式指定 resultMap。比如:


  
  1. <select id="selectUsers" resultType="map">
  2. select id, username, password
  3. from t_user
  4. where id = #{id}
  5. </select>

或者,我们用一个实例对象 来接收数据库的查询结果


  
  1. <select id="selectUsers" resultType="User">
  2. select *
  3. from t_user
  4. where id = #{id}
  5. </select>

但是,上述条件是 数据库 表的列名 与 实例对象的属性名是一致的情况。如果二者不一致呢?该如何去做?

我们面试的时候,经常会遇到有面试官会问,数据库表的字段名和 实体对象的属性名不一致,我们如何操作,

其实解决这个问题有很多办法。

比如 利用SQL语法里的 as


  
  1. <select id="selectUsers" resultType="User">
  2. select
  3. user_id as "id",
  4. user_name as "userName",
  5. user_password as "password"
  6. from some_table
  7. where id = #{id}
  8. </select>

我们还可以显示的配置一个外部resultMap  这也是解决列名不匹配的另外一种方式。


  
  1. <!--
  2. resultMap:设置自定义映射
  3. 属性:
  4. id:表示自定义映射的唯一标识
  5. type:查询的数据要映射的实体类的类型
  6. 子标签:
  7. id:设置主键的映射关系
  8. result:设置普通字段的映射关系
  9. association:设置多对一的映射关系
  10. collection:设置一对多的映射关系
  11. 属性:
  12. property:设置映射关系中实体类中的属性名
  13. column:设置映射关系中表中的字段名
  14. -->
  15. <resultMap id="userMap" type="user">
  16. <id property="id" column="id"> </id>
  17. <result property="userName" column="username"> </result>
  18. <result property="passWord" column="password"> </result>
  19. <result property="age" column="age"> </result>
  20. <result property="gender" column="gender"> </result>
  21. </resultMap>
  22. <select id="getMohu" resultMap="userMap" >
  23. <!-- select * from t_user where gender like '%${keyword}%'-->
  24. <!--select * from t_user where username like concat('%',#{keyword},'%')-->
  25. select * from t_user where email like "%"#{keyword}"%"
  26. </select>

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

此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系:

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

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

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

1.2、多对一映射处理

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

1.2.1 级联方式处理映射信息

我们先看一下 用原生Sql语句实现的效果:

SELECT emp.* ,dept.* FROM t_emp emp LEFT JOIN t_dept dept ON emp.`dept_id`=dept.`dept_id` WHERE emp.`emp_id`=1;

 

代码实现:


  
  1. public class Emp{
  2. private Integer eid;
  3. private String ename;
  4. private Integer age;
  5. private String gender;
  6. private Dept dept;
  7. @Override
  8. public String toString () {
  9. return "Emp{" +
  10. "eid=" + eid +
  11. ", ename='" + ename + '\'' +
  12. ", age=" + age +
  13. ", dept=" + dept +
  14. ", gender='" + gender + '\'' +
  15. '}';
  16. }
  17. public Integer getEid () {
  18. return eid;
  19. }
  20. public void setEid (Integer eid) {
  21. this.eid = eid;
  22. }
  23. public String getEname () {
  24. return ename;
  25. }
  26. public void setEname (String ename) {
  27. this.ename = ename;
  28. }
  29. public Integer getAge () {
  30. return age;
  31. }
  32. public void setAge (Integer age) {
  33. this.age = age;
  34. }
  35. public String getGender () {
  36. return gender;
  37. }
  38. public void setGender (String gender) {
  39. this.gender = gender;
  40. }
  41. }


  
  1. public class Dept {
  2. private Integer did;
  3. private String dname;
  4. public String getDname () {
  5. return dname;
  6. }
  7. public void setDname (String dname) {
  8. this.dname = dname;
  9. }
  10. public Integer getDid () {
  11. return did;
  12. }
  13. public void setDid (Integer did) {
  14. this.did = did;
  15. }
  16. @Override
  17. public String toString () {
  18. return "dept{" +
  19. "did=" + did +
  20. ", dname='" + dname + '\'' +
  21. '}';
  22. }
  23. }

接口添加方法:

  Emp getEmpAndDeptByEid(@Param("id")int id);


  
  1. <resultMap id="empDeptMap" type="Emp">
  2. <id column="emp_id" property="eid"> </id>
  3. <result column="emp_name" property="ename"> </result>
  4. <result column="age" property="age"> </result>
  5. <result column="gender" property="gender"> </result>
  6. <result column="dept_id" property="dept.did"> </result>
  7. <result column="dept_name" property="dept.dname"> </result>
  8. </resultMap>
  9. <!-- getEmpAndDeptByEid-->
  10. <select id="getEmpAndDeptByEid" resultMap="empDeptMap">
  11. SELECT emp.* ,dept.* FROM t_emp emp LEFT JOIN t_dept dept ON emp.`dept_id`=dept.`dept_id` WHERE emp.`emp_id`=#{id}
  12. </select>

测试输出:

输出:

 Emp{eid=1, ename='小黑', age=20, dept=dept{did=1, dname='A'}, gender='女'}

1.2.2、使用association处理映射关系


  
  1. <resultMap id="empDeptMap" type="Emp">
  2. <id column="emp_id" property="eid"> </id>
  3. <result column="emp_name" property="ename"> </result>
  4. <result column="age" property="age"> </result>
  5. <result column="gender" property="gender"> </result>
  6. <association property="dept" javaType="Dept">
  7. <id column="dept_id" property="did"> </id>
  8. <result column="dept_name" property="dname"> </result>
  9. </association>
  10. </resultMap>

1.2.3 分步查询

建立两个实体 Emp 和 Dept 分别代表 员工和 部门。

建立对应的mapper接口。

创建对应的接口映射文件

此处我作为简化,把分步查询放在了同一个接口 和映射文件中 (EmpMapper.java 和 EmpMapper.xml)

①查询员工信息


  
  1. public interface EmpMapper {
  2. /**
  3. * 通过分步查询查询员工信息
  4. * 分步查询:查询员工以及所在部门信息的第一步
  5. * @param eid
  6. * @return
  7. */
  8. Emp getEmpByStep1 (@Param("eid") int eid);
  9. /**
  10. * 分步查询的第二步: 根据员工所对应的dept_id 查询部门信息
  11. * @param did
  12. * @return
  13. */
  14. Dept getEmpDeptByStep2 (@Param("did") int did);
  15. }

  
  1. <resultMap id="empDeptStepMap" type="Emp">
  2. <id column="emp_id" property="eid"> </id>
  3. <result column="emp_name" property="ename"> </result>
  4. <result column="age" property="age"> </result>
  5. <result column="gender" property="gender"> </result>
  6. <!--
  7. select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
  8. column:将sql以及查询结果中的某个字段设置为分步查询的条件
  9. -->
  10. <association property="dept" fetchType="eager"
  11. select= "com.alex.mybatis.mapper.EmpMapper.getEmpDeptByStep2" column= "dept_id" > </association>
  12. </resultMap>
  13. <!--Emp getEmpByStep1(@Param("eid") int eid);-->
  14. <select id="getEmpByStep1" resultMap="empDeptStepMap">
  15. select * from t_emp where emp_id = #{eid}
  16. </select>
  17. <!--Dept getEmpDeptByStep2(@Param("did") int did);-->
  18. <resultMap id="deptMap" type="Dept">
  19. <id column="dept_id" property="did"> </id>
  20. <result column="dept_name" property="dname"> </result>
  21. </resultMap>
  22. <select id="getEmpDeptByStep2" resultMap="deptMap" >
  23. select * from t_dept where dept_id = #{did}
  24. </select>

可以这样理解:

t_emp和t_dept 是外键包含关系,传统意义上来说,我们查询的时候,要进行外连接。

我们现在如果想得到员工的个人信息,以及所在部门的个人信息(以实体对象的形式获得查询结果),可以分步进行。

1)我们根据 eid 获取 从 t_emp 表中查询到的 员工数据 执行 step1方法,构建  员工实体对象 emp

2) 由于Emp实体对象里,包含一个属性 Dept 类型的 dept对象, 而表数据,只能给到我们 具体的部门编号did。( did 是Dept对象的属性之一)

3)所以,我们要拿着这个did 去部门表t_dept 里查询部门信息。此时 就利用了 association 标签里的 select 去执行 step2方法 (column =dept_id 填写的是 分步查询条件的数据库字段名,property 填写的是 Emp对象 当前要被分步查询的属性名)

4)Emp实例对象构建完成,返回最终执行结果

 

 Emp{eid=1, ename='小黑', age=20, dept=Dept{did=1, dname='A'}, gender='女'}

注意事项: 一定要 注意,对象属性名是否与表字段名一一对应,否则很有可能会报nullPoint 或查不到数据,

1.3 一对多映射处理

修改 Dept 如下


  
  1. import java.util.List;
  2. public class Dept {
  3. private Integer did;
  4. private String dname;
  5. private List<Emp> emps; //多对一映射 一个部门可以有多个员工
  6. @Override
  7. public String toString () {
  8. return "Dept{" +
  9. "did=" + did +
  10. ", dname='" + dname + '\'' +
  11. ", emps=" + emps +
  12. '}';
  13. }
  14. public List<Emp> getEmps () {
  15. return emps;
  16. }
  17. public void setEmps (List<Emp> emps) {
  18. this.emps = emps;
  19. }
  20. public String getDname () {
  21. return dname;
  22. }
  23. public void setDname (String dname) {
  24. this.dname = dname;
  25. }
  26. public Integer getDid () {
  27. return did;
  28. }
  29. public void setDid (Integer did) {
  30. this.did = did;
  31. }
  32. }

1.3.1、collection


  
  1. public interface DeptMapper {
  2. /**
  3. * 根据部门id查新部门以及部门中的员工信息
  4. * * @param did
  5. * * @return
  6. */
  7. Dept getDeptEmpById (@Param("did") int did);
  8. }

  
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.alex.mybatis.mapper.DeptMapper">
  6. <resultMap id="DeptMap" type="Dept">
  7. <id property="did" column="dept_id"> </id>
  8. <result property="dname" column="dept_name"> </result>
  9. <!--
  10. ofType:设置collection标签所处理的集合属性中存储数据的类型
  11. -->
  12. <collection property="emps" ofType="Emp">
  13. <id property="eid" column="emp_id"> </id>
  14. <result property="ename" column="emp_name"> </result>
  15. <result property="age" column="age"> </result>
  16. <result property="gender" column="gender"> </result>
  17. <!-- <result property="dept.did" column="dept_id"></result>-->
  18. <!-- <result property="dept.dname" column="dept_name"></result>-->
  19. </collection>
  20. </resultMap>
  21. <select id="getDeptEmpById" resultMap="DeptMap">
  22. select dept.*,emp.* from t_dept dept left join t_emp emp on dept.dept_id = emp.dept_id where dept.dept_id =#{did}
  23. </select>
  24. </mapper>

输出结果


Dept{did=1, dname='A', emps=[Emp{eid=1, ename='小黑', age=20, dept=null, gender='女'}, Emp{eid=4, ename='赵六', age=26, dept=null, gender='男'}]}

1.3.2 分步查询

我们捋一捋思路:

现在 两个关系中,谁是多,谁是1?

根据部门编号,查询该部门全部员工,显然 部门是1,员工是多。

而且我们在Dept类中也表现出来了:

这种分步查询,其实效果类似子查询,更具体的说是一种相关子查询。

t_dept 的数据要代入到 t_emp中查询结果,所以 t_emp是被驱动表,t_dept 是驱动表。 小表驱动大表

 那么,我们分步查询的步骤就是这样:

1)先查询t_dept 的 部门信息

2)再将dept_id的值带入 t_emp 查询员工信息。

DeptMapper 接口


  
  1. /**
  2. * 分步查询1: 根据did 查询部门信息
  3. */
  4. Dept getDeptEmpStep1 (@Param("did") int did);

EmpMapper 接口


  
  1. /**
  2. *
  3. * 通过分步查询 部门的具体信息(该部门的所有信息包括员工信息)
  4. */
  5. Emp getDeptEmpStep2 (@Param("did") int did);

DeptMapper.xml


  
  1. !-- 分步查询 查询部门全部信息-->
  2. <resultMap id="DeptEmpMap" type="Dept">
  3. <id property="did" column="dept_id"> </id>
  4. <result property="dname" column="dept_name"> </result>
  5. <collection property="emps" fetchType="eager"
  6. select= "com.alex.mybatis.mapper.EmpMapper.getDeptEmpStep2" column= "dept_id"> </collection>
  7. </resultMap>
  8. <select id="getDeptEmpStep1" resultMap="DeptEmpMap">
  9. select * from t_dept where dept_id =#{did}
  10. </select>

EmpMapper.xml


  
  1. <!-- 2分步查询 查询部门全部信息-->
  2. <resultMap id="empDeptMap" type="Emp">
  3. <id column="emp_id" property="eid"> </id>
  4. <result column="emp_name" property="ename"> </result>
  5. <result column="age" property="age"> </result>
  6. <result column="gender" property="gender"> </result>
  7. <association property="dept" javaType="Dept">
  8. <id column="dept_id" property="did"> </id>
  9. <result column="dept_name" property="dname"> </result>
  10. </association>
  11. </resultMap>
  12. <select id="getDeptEmpStep2" resultMap="empDeptMap">
  13. select * from t_emp where dept_id =#{did}
  14. </select>

测试输出:

 Dept{did=1, dname='A',

emps=[Emp{eid=1, ename='小黑', age=20, dept=Dept{did=1, dname='null', emps=null}, gender='女'},

            Emp{eid=4, ename='赵六', age=26, dept=Dept{did=1, dname='null', emps=null}, gender='男'}]}

代码仓库:https://github.com/Chai-Feng/git-demo01.git


转载:https://blog.csdn.net/Alex_cf/article/details/128760753
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场