Mybatis篇-(四)映射文件

﹏ヽ暗。殇╰゛Y 2023-10-04 12:35 122阅读 0赞

四、Mybatis-映射文件

增删改查

mapper.xml

  1. <mapper namespace="com.cvzhanshi.mybatis.dao.EmployeeMapper">
  2. <select id="getEmpById" resultType="com.cvzhanshi.mybatis.entity.Employee">
  3. select id,last_name lastName,email,gender from employee where id = #{id}
  4. </select>
  5. <!-- public void addEmp(Employee employee); -->
  6. <!-- parameterType:参数类型,可以省略,
  7. <insert id="addEmp" parameterType="com.cvzhanshi.mybatis.entity.Employee">
  8. insert into employee(last_name,email,gender)
  9. values(#{lastName},#{email},#{gender})
  10. </insert>
  11. <!-- public void updateEmp(Employee employee); -->
  12. <update id="updateEmp">
  13. update employee
  14. set last_name=#{lastName},email=#{email},gender=#{gender}
  15. where id=#{id}
  16. </update>
  17. <!-- public void deleteEmpById(Integer id); -->
  18. <delete id="deleteEmpById">
  19. delete from employee where id=#{id}
  20. </delete>
  21. </mapper>

EmployeeMapper.java接口

  1. public interface EmployeeMapper {
  2. public Employee getEmpById(Integer id);
  3. public Long addEmp(Employee employee);
  4. public boolean updateEmp(Employee employee);
  5. public void deleteEmpById(Integer id);
  6. }

测试:

  1. @Test
  2. public void test03() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. //1、获取到的SqlSession不会自动提交数据
  5. SqlSession openSession = sqlSessionFactory.openSession();
  6. try{
  7. EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
  8. //测试添加
  9. // Employee employee = new Employee(null, "jerry4",null, "1");
  10. // mapper.addEmp(employee);
  11. // System.out.println(employee.getId());
  12. //测试修改
  13. // Employee employee = new Employee(1, "Tom", "jerry@atguigu.com", "0");
  14. // boolean updateEmp = mapper.updateEmp(employee);
  15. // System.out.println(updateEmp);
  16. //测试删除
  17. mapper.deleteEmpById(2);
  18. //2、手动提交数据
  19. openSession.commit();
  20. }finally{
  21. openSession.close();
  22. }
  23. }

说明:

  • mybatis允许增删改直接定义以下类型返回值

    • Integer(影响的行数)、Long(影响的行数)、Boolean(操作是否成功)、void
  • 我们需要手动提交数据

    • sqlSessionFactory.openSession();===》手动提交
    • sqlSessionFactory.openSession(true);===》自动提交

获取自增主键的值

若数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),则可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上

mapper.xml

  1. <insert id="addEmp" parameterType="com.cvzhanshi.mybatis.entity.Employee"
  2. useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
  3. insert into employee(last_name,email,gender)
  4. values(#{lastName},#{email},#{gender})
  5. </insert>

说明:

  • mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys();
  • useGeneratedKeys=“true”;使用自增主键获取主键值策略
  • keyProperty;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性

测试:

  1. @Test
  2. public void test03() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. //1、获取到的SqlSession不会自动提交数据
  5. SqlSession openSession = sqlSessionFactory.openSession();
  6. try{
  7. EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
  8. //测试添加
  9. Employee employee = new Employee(null, "cvzhanshi","cvzhanshi@qq.com", "1");
  10. System.out.println("操作前-----" + employee.getId());
  11. mapper.addEmp(employee);
  12. System.out.println("操作后-----" + employee.getId());
  13. //2、手动提交数据
  14. openSession.commit();
  15. }finally{
  16. openSession.close();
  17. }
  18. }

运行效果:
在这里插入图片描述

获取非自增主键的值

对于不支持自增型主键的数据库(例如 Oracle),则可以使用 selectKey 子元素: selectKey 元素将会首先运行,id 会被设置,然 后插入语句会被调用

mapper.xml

  1. <!--
  2. 获取非自增主键的值:
  3. Oracle不支持自增;Oracle使用序列来模拟自增;
  4. 每次插入的数据的主键是从序列中拿到的值;如何获取到这个值;
  5. -->
  6. <insert id="addEmp" databaseId="oracle">
  7. <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
  8. <!-- 编写查询主键的sql语句 -->
  9. <!-- BEFORE-->
  10. select EMPLOYEES_SEQ.nextval from dual
  11. <!-- AFTER:
  12. select EMPLOYEES_SEQ.currval from dual -->
  13. </selectKey>
  14. <!-- 插入时的主键是从序列中拿到的 -->
  15. <!-- BEFORE:-->
  16. insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL)
  17. values(#{id},#{lastName},#{email})
  18. <!-- AFTER:
  19. insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL)
  20. values(employees_seq.nextval,#{lastName},#{email}) -->
  21. </insert>

selectKey






















属性 作用
keyProperty 查出的主键值封装给javaBean的哪个属性
order “BEFORE”:当前sql在插入sql之前运行
AFTER:当前sql在插入sql之后运行
resultType 查出的数据的返回值类型

BEFORE运行顺序:
先运行selectKey查询id的sql;查出id值封装给javaBean的id属性
在运行插入的sql;就可以取出id属性对应的值
AFTER运行顺序:
先运行插入的sql(从序列中取出新值作为id);
再运行selectKey查询id的sql;

参数处理

参数的传递

  • 单个参数:mybatis不会做特殊处理

    • #{参数名/任意名}:取出参数值
  • 多个参数:mybatis会做特殊处理

    • 任意多个参数,都会被MyBatis重新包装成一个Map传入。 Map的key是param1,param2,0,1…,值就是参数的值
    • 操作时的异常

      异常:

      1. org.apache.ibatis.binding.BindingException:
      2. Parameter 'id' not found.
      3. Available parameters are [1, 0, param1, param2]
      4. 操作:
      5. 方法:public Employee getEmpByIdAndLastName(Integer id,String lastName);
      6. 取值:#{
      7. id},#{
      8. lastName}
  • 命名参数

    • 为参数使用@Param起一个名字,MyBatis就会将这些参数封 装进map中,key就是我们自己指定的名字
    • 使用:@Param(“id”)———> #{指定的key}取出对应的参数值(key:使用@Param注解指定的值、value:参数值)
  • POJO

    • 当这些参数属于我们业务POJO时,我们直接传递POJO
    • #{属性名}:取出传入的pojo的属性值
  • Map

    • 如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map
    • #{key}:取出map中对应的值
  • TO

    • 如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象

      Page{

      1. int index;
      2. int size;

      }

思考案例

  • public Employee getEmp(@Param(“id”)Integer id,String lastName);

    • 取值:id==>#{id/param1} lastName==>#{param2}
  • public Employee getEmp(Integer id,@Param(“e”)Employee emp);

    • 取值:id==>#{param1} lastName===>#{param2.lastName/e.lastName}

特别注意:如果是Collection(List、Set)类型或者是数组,
也会特殊处理。也是把传入的list或者数组封装在map中。
key:Collection(collection),如果是List还可以使用这个key(list)、数组(array)

  • public Employee getEmpById(List<Integer>ids);

    • 取值:取出第一个id的值: #{list[0]}

结合源码,看看mybatis如何处理参数

总结:参数多时会封装map,为了不混乱,我们可以使用@Param来指定封装时使用的key
#{key}就可以取出map中的值;

解析:

传入的参数 (@Param(“id”)Integer id,@Param(“lastName”)String lastName);

ParamNameResolver解析参数封装map的;

  • names:{0=id, 1=lastName};构造器的时候就确定好了

    • 确定流程

      • 获取每个标了param注解的参数的@Param的值:id,lastName; 赋值给name
      • 每次解析一个参数给map中保存信息:(key:参数索引,value:name的值)

        • name的值:

          • 标注了param注解:注解的值
          • 没有标注

            • 全局配置:useActualParamName(jdk1.8):name=参数名
            • name=map.size();相当于当前元素的索引
        • 类似于{0=id, 1=lastName,2=2}

    // 传入的参数 args【1,”Tom”,’hello’】:
    //1、参数为null直接返回
    //2、如果只有一个元素,并且没有Param注解;args[0]:单个参数直接返回
    //3、多个元素或者有Param标注
    //3.1、遍历names集合;{0=id, 1=lastName,2=2}

    1. //names集合的value作为key; names集合的key又作为取值的参考args[0]:args【1,"Tom"】:
    2. //eg:{id=args[0]:1,lastName=args[1]:Tom,2=args[2]}
    3. //额外的将每一个参数也保存到map中,使用新的key:param1...paramN
    4. //效果:有Param注解可以#{指定的key},或者#{param1}

    public Object getNamedParams(Object[] args) {

    1. final int paramCount = names.size();
    2. //1、参数为null直接返回
    3. if (args == null || paramCount == 0) {
    4. return null;
    5. //2、如果只有一个元素,并且没有Param注解;args[0]:单个参数直接返回
    6. } else if (!hasParamAnnotation && paramCount == 1) {
    7. return args[names.firstKey()];
    8. //3、多个元素或者有Param标注
    9. } else {
    10. final Map<String, Object> param = new ParamMap<Object>();
    11. int i = 0;
    12. //4、遍历names集合;{0=id, 1=lastName,2=2}
    13. for (Map.Entry<Integer, String> entry : names.entrySet()) {
  1. //names集合的value作为key; names集合的key又作为取值的参考args[0]:args【1,"Tom"】:
  2. //eg:{id=args[0]:1,lastName=args[1]:Tom,2=args[2]}
  3. param.put(entry.getValue(), args[entry.getKey()]);
  4. // add generic param names (param1, param2, ...)param
  5. //额外的将每一个参数也保存到map中,使用新的key:param1...paramN
  6. //效果:有Param注解可以#{指定的key},或者#{param1}
  7. final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
  8. // ensure not to overwrite parameter named with @Param
  9. if (!names.containsValue(genericParamName)) {
  10. param.put(genericParamName, args[entry.getKey()]);
  11. }
  12. i++;
  13. }
  14. return param;
  15. }
  16. }
  17. }

$和#的取值区别

  • #{}:可以获取map中的值或者pojo对象属性的值
  • ${}:可以获取map中的值或者pojo对象属性的值

    select from tbl_employee where id=${id} and last_name=#{lastName}
    Preparing: select
    from tbl_employee where id=2 and last_name=?

区别

  • #{}:是以预编译的形式,将参数设置到sql语句中;PreparedStatement;防止sql注入
  • ${}:取出的值直接拼装在sql语句中;会有安全问题(sql注入问题,和starment差不多)

大多情况下,我们去参数的值都应该去使用#{}

原生jdbc不支持占位符的地方我们就可以使用${}进行取值

比如分表、排序。。。;按照年份分表拆分

select * from ${year}_salary where xxx;
select * from tbl_employee order by ${f_name} ${order}

#{}:更丰富的用法–jdbcType

规定参数的一些规则:

javaType、 jdbcType、 mode(存储过程)、 numericScale、
resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能)

jdbcType通常需要在某种特定的条件下被设置:

在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle(报错)

JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生Jdbc的OTHER类型,oracle不能正确处理

由于全局配置中:jdbcTypeForNull=OTHER;oracle不支持;两种办法

  • #{email,jdbcType=OTHER}
  • jdbcTypeForNull=NULL
    在全局配置文件中配置<setting name="jdbcTypeForNull" value="NULL"/>

Select

  • Select元素来定义查询操作
  • Id:唯一标识符

    • – 用来引用这条语句,需要和接口的方法名一致
  • parameterType:参数类型

    • 可以不传,MyBatis会根据TypeHandler自动推断
  • resultType:返回值类型

    • 别名或者全类名,如果返回的是集合,定义集合中元 素的类型。不能和resultMap同时使用

selcet返回list

resultType:如果返回的是一个集合,要写集合中元素的类型

示例:

marpper.xml

  1. <!-- (对应接口的方法)public List<Employee> getEmpsByLastNameLike(String lastName); -->
  2. <!--resultType:如果返回的是一个集合,要写集合中元素的类型 -->
  3. <select id="getEmpsByLastNameLike" resultType="com.cvzhanshi.mybatis.entity.Employee">
  4. select * from employee where last_name like #{lastName}
  5. </select>

测试

  1. @Test
  2. public void test04() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. //1、获取到的SqlSession不会自动提交数据
  5. SqlSession openSession = sqlSessionFactory.openSession();
  6. try{
  7. EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
  8. List<Employee> like = mapper.getEmpsByLastNameLike("%s%");
  9. for (Employee employee : like) {
  10. System.out.println(employee);
  11. }
  12. }finally{
  13. openSession.close();
  14. }
  15. }

测试结果:
在这里插入图片描述

记录封装成map

返回一条记录的map;key就是列名,值就是对应的值

resultType为map

mapper.xml

  1. <!--对应接口中的方法->
  2. <!--public Map<String, Object> getEmpByIdReturnMap(Integer id); -->
  3. <select id="getEmpByIdReturnMap" resultType="map">
  4. select * from tbl_employee where id=#{id}
  5. </select>

测试:

  1. @Test
  2. public void test04() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. //1、获取到的SqlSession不会自动提交数据
  5. SqlSession openSession = sqlSessionFactory.openSession();
  6. try{
  7. EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
  8. Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
  9. System.out.println(map);
  10. }finally{
  11. openSession.close();
  12. }
  13. }

测试结果
在这里插入图片描述

多条记录封装一个map:Map:键是这条记录的一个属性名,值是记录封装后的javaBean

@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key

resultType为javaBean的全类名

接口方法中

  1. //多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
  2. //@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
  3. @MapKey("lastName")
  4. public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);

mapper.xml

  1. <!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName); -->
  2. <select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
  3. select * from employee where last_name like #{lastName}
  4. </select>

测试

  1. @Test
  2. public void test04() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. //1、获取到的SqlSession不会自动提交数据
  5. SqlSession openSession = sqlSessionFactory.openSession();
  6. try{
  7. EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
  8. Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%s%");
  9. Set<String> strings = map.keySet();
  10. Iterator<String> iterator = strings.iterator();
  11. while ((iterator.hasNext())){
  12. String next = iterator.next();
  13. System.out.println(next+ "=" +map.get(next));
  14. }
  15. }finally{
  16. openSession.close();
  17. }
  18. }

测试效果:
在这里插入图片描述

resultMap-自定义结果映射规则

使用场景:当mysql中表的列名与javaBean的属性名不对应时有两种解决方法:

  • 数据库字段命名规范,POJO属性符合驼峰命名法,如 A_COLUMNaColumn,我们可以开启自动驼峰命名规 则映射功能,mapUnderscoreToCamelCase=true
  • 使用resultMap自定义映射规则
  • resultMap

    • type:自定义规则的Java类型
    • id:唯一id方便引用
    1. <resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp">
    2. <!--指定主键列的封装规则
    3. id定义主键会底层有优化;
    4. column:指定哪一列
    5. property:指定对应的javaBean属性
    6. -->
    7. <id column="id" property="id"/>
    8. <!-- 定义普通列封装规则 -->
    9. <result column="last_name" property="lastName"/>
    10. <!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
    11. <result column="email" property="email"/>
    12. <result column="gender" property="gender"/>
    13. </resultMap>
    14. <!-- resultMap:自定义结果集映射规则; -->
    15. <!-- public Employee getEmpById(Integer id); -->
    16. <select id="getEmpById" resultMap="MySimpleEmp">
    17. select * from employee where id=#{id}
    18. </select>

测试

使用了resultMap
在这里插入图片描述

未使用则lastName为Null

resultMap-关联查询

级联属性封装结果

场景一:

查询Employee的同时查询员工对应的部门 Employee===Department 一个员工有与之对应的部门信息; id last_name gender d_id did dept_name (private Department dept;)

  1. public class Employee {
  2. private Integer id;
  3. private String lastName;
  4. private String email;
  5. private String gender;
  6. private Department dept;
  7. }
  8. public class Department {
  9. private Integer id;
  10. private String departmentName;
  11. }

xml

  1. <!--
  2. 联合查询:级联属性封装结果集
  3. -->
  4. <resultMap type="com.cvzhanshi.mybatis.entity.Employee" id="MyDifEmp">
  5. <id column="id" property="id"/>
  6. <result column="last_name" property="lastName"/>
  7. <result column="gender" property="gender"/>
  8. <result column="did" property="dept.id"/>
  9. <result column="dept_name" property="dept.departmentName"/>
  10. </resultMap>
  11. <!-- public Employee getEmpAndDept(Integer id);-->
  12. <select id="getEmpAndDept" resultMap="MyDifEmp2">
  13. SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
  14. d.id did,d.dept_name dept_name FROM employee e,dept d
  15. WHERE e.d_id=d.id AND e.id=#{id}
  16. </select>

测试

  1. @Test
  2. public void test05() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
  7. Employee empById = mapper.getEmpAndDept(1);
  8. System.out.println(empById);
  9. }finally{
  10. sqlSession.close();
  11. }
  12. }

运行效果
在这里插入图片描述

association定义关联的单个对象的封装规则

场景一:

查询Employee的同时查询员工对应的部门 Employee===Department 一个员工有与之对应的部门信息; id last_name gender d_id did dept_name (private Department dept;)

  1. <!--
  2. 使用association定义关联的单个对象的封装规则;
  3. -->
  4. <resultMap type="com.cvzhanshi.mybatis.entity.Employee" id="MyDifEmp2">
  5. <id column="id" property="id"/>
  6. <result column="last_name" property="lastName"/>
  7. <result column="gender" property="gender"/>
  8. <!-- association可以指定联合的javaBean对象
  9. property="dept":指定哪个属性是联合的对象
  10. javaType:指定这个属性对象的类型[不能省略]
  11. column:对应查询结果哪个列
  12. -->
  13. <association property="dept" javaType="com.cvzhanshi.mybatis.entity.Department">
  14. <id column="did" property="id"/>
  15. <result column="dept_name" property="departmentName"/>
  16. </association>
  17. </resultMap>
  18. <!-- public Employee getEmpAndDept(Integer id);-->
  19. <select id="getEmpAndDept" resultMap="MyDifEmp2">
  20. SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
  21. d.id did,d.dept_name dept_name FROM employee e,dept d
  22. WHERE e.d_id=d.id AND e.id=#{id}
  23. </select>

运行结果:
在这里插入图片描述

association进行分步查询

xml

  1. <!-- 使用association进行分步查询:
  2. 1、先按照员工id查询员工信息
  3. 2、根据查询员工信息中的d_id值去部门表查出部门信息
  4. 3、部门设置到员工中;
  5. -->
  6. <!-- id last_name email gender d_id -->
  7. <resultMap type="com.cvzhanshi.mybatis.entity.Employee" id="MyEmpByStep">
  8. <id column="id" property="id"/>
  9. <result column="last_name" property="lastName"/>
  10. <result column="email" property="email"/>
  11. <result column="gender" property="gender"/>
  12. <!-- association定义关联对象的封装规则
  13. select:表明当前属性是调用select指定的方法查出的结果
  14. column:指定将哪一列的值传给这个方法()用作参数
  15. 流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
  16. -->
  17. <association property="dept"
  18. select="com.cvzhanshi.mybatis.dao.DepartmentMapper.getDeptById"
  19. column="d_id">
  20. </association>
  21. </resultMap>
  22. <!-- public Employee getEmpByIdStep(Integer id);-->
  23. <select id="getEmpByIdStep" resultMap="MyEmpByStep">
  24. select * from employee where id=#{id}
  25. </select>

DepartmentMapper.java

  1. public interface DepartmentMapper {
  2. public Department getDeptById(Integer id);
  3. }

DepartmentMapper.xml

  1. <mapper namespace="com.cvzhanshi.mybatis.dao.DepartmentMapper">
  2. <!--public Department getDeptById(Integer id); -->
  3. <select id="getDeptById" resultType="com.cvzhanshi.mybatis.entity.Department">
  4. select id,dept_name departmentName from dept where id=#{id}
  5. </select>
  6. </mapper>

测试

  1. @Test
  2. public void test05() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
  7. Employee empByIdStep = mapper.getEmpByIdStep(4);
  8. System.out.println(empByIdStep);
  9. System.out.println(empByIdStep.getDept());
  10. }finally{
  11. sqlSession.close();
  12. }
  13. }

运行结果
在这里插入图片描述

association-分段查询&延迟加载

用分段查询的代码 只需要在全局文件中配置一下属性

Employee==>Dept:
我们每次查询Employee对象的时候,都将一起查询出来。
部门信息在我们使用的时候再去查询;
分段查询的基础之上加上两个配置:

  1. <settings>
  2. <!--开启延迟加载和属性按需加载-->
  3. <!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 -->
  4. <setting name="lazyLoadingEnabled" value="true"/>
  5. <setting name="aggressiveLazyLoading" value="false"/>
  6. </settings>

测试

  1. @Test
  2. public void test05() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
  7. Employee empByIdStep = mapper.getEmpByIdStep(4);
  8. //只要employee的lastname属性
  9. System.out.println(empByIdStep.getLastName());
  10. }finally{
  11. sqlSession.close();
  12. }
  13. }

未配置
在这里插入图片描述

发送了两条查询sql,并没有按需加载

配置了
在这里插入图片描述

只发送了一条查询employee的sql,达到了按需加载延迟加载

collection定义关联集合封装规则

场景二: 查询部门的时候将部门对应的所有员工信息也查询出来

Department.java

  1. public class Department {
  2. private Integer id;
  3. private String departmentName;
  4. private List<Employee> emps;
  5. ...
  6. }

DepartmentMapper.xml

  1. <!--
  2. public class Department {
  3. private Integer id;
  4. private String departmentName;
  5. private List<Employee> emps;
  6. did dept_name || eid last_name email gender
  7. -->
  8. <!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则 -->
  9. <resultMap type="com.cvzhanshi.mybatis.entity.Department" id="MyDept">
  10. <id column="did" property="id"/>
  11. <result column="dept_name" property="departmentName"/>
  12. <!--
  13. collection定义关联集合类型的属性的封装规则
  14. ofType:指定集合里面元素的类型
  15. -->
  16. <collection property="emps" ofType="com.cvzhanshi.mybatis.entity.Employee">
  17. <!-- 定义这个集合中元素的封装规则 -->
  18. <id column="eid" property="id"/>
  19. <result column="last_name" property="lastName"/>
  20. <result column="email" property="email"/>
  21. <result column="gender" property="gender"/>
  22. </collection>
  23. </resultMap>
  24. <!-- public Department getDeptByIdPlus(Integer id); -->
  25. <select id="getDeptByIdPlus" resultMap="MyDept">
  26. SELECT d.id did,d.dept_name dept_name,
  27. e.id eid,e.last_name last_name,e.email email,e.gender gender
  28. FROM dept d
  29. LEFT JOIN employee e
  30. ON d.id=e.d_id
  31. WHERE d.id=#{id}
  32. </select>

测试

  1. @Test
  2. public void test06() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
  7. Department deptByIdPlus = mapper.getDeptByIdPlus(1);
  8. System.out.println(deptByIdPlus);
  9. System.out.println(deptByIdPlus.getEmps());
  10. }finally{
  11. sqlSession.close();
  12. }
  13. }

运行效果
在这里插入图片描述

collection分段查询&延迟加载

DepartmentMapper.xml

  1. <!-- collection:分段查询 -->
  2. <resultMap type="com.cvzhanshi.mybatis.entity.Department" id="MyDeptStep">
  3. <id column="id" property="id"/>
  4. <id column="dept_name" property="departmentName"/>
  5. <collection property="emps"
  6. select="com.cvzhanshi.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"
  7. column="{deptId=id}" fetchType="lazy"></collection>
  8. </resultMap>
  9. <!-- public Department getDeptByIdStep(Integer id); -->
  10. <select id="getDeptByIdStep" resultMap="MyDeptStep">
  11. select id,dept_name from dept where id=#{id}
  12. </select>

EmployeeMapperPlus.xml

  1. <!-- public List<Employee> getEmpsByDeptId(Integer deptId); -->
  2. <select id="getEmpsByDeptId" resultType="com.cvzhanshi.mybatis.entity.Employee">
  3. select * from employee where d_id=#{deptId}
  4. </select>

测试

  1. @Test
  2. public void test06() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
  7. Department deptByIdStep = mapper.getDeptByIdStep(1);
  8. System.out.println(deptByIdStep.getDepartmentName());
  9. System.out.println(deptByIdStep.getEmps());
  10. }finally{
  11. sqlSession.close();
  12. }
  13. }

运行效果
在这里插入图片描述

扩展:多列的值传递过去:

将多列的值封装map传递; column=”{key1=column1,key2=column2}

“fetchType=“lazy”:表示使用延迟加载; - lazy:延迟 - eager:立即

discriminator鉴别器

情景:

封装Employee:
如果查出的是女生:就把部门信息查询出来,否则不查询;
如果是男生,把last_name这一列的值赋值给email;

EmployeeMapperPlus.xml

  1. <!-- =======================鉴别器============================ -->
  2. <!-- <discriminator javaType=""></discriminator>
  3. 鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
  4. 封装Employee:
  5. 如果查出的是女生:就把部门信息查询出来,否则不查询;
  6. 如果是男生,把last_name这一列的值赋值给email;
  7. -->
  8. <resultMap type="com.cvzhanshi.mybatis.entity.Employee" id="MyEmpDis">
  9. <id column="id" property="id"/>
  10. <result column="last_name" property="lastName"/>
  11. <result column="email" property="email"/>
  12. <result column="gender" property="gender"/>
  13. <!--
  14. column:指定判定的列名
  15. javaType:列值对应的java类型 -->
  16. <discriminator javaType="string" column="gender">
  17. <!--女生 resultType:指定封装的结果类型;不能缺少。/resultMap-->
  18. <case value="0" resultType="com.cvzhanshi.mybatis.entity.Employee">
  19. <association property="dept"
  20. select="com.cvzhanshi.mybatis.dao.DepartmentMapper.getDeptById"
  21. column="d_id">
  22. </association>
  23. </case>
  24. <!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
  25. <case value="1" resultType="com.cvzhanshi.mybatis.entity.Employee">
  26. <id column="id" property="id"/>
  27. <result column="last_name" property="lastName"/>
  28. <result column="last_name" property="email"/>
  29. <result column="gender" property="gender"/>
  30. </case>
  31. </discriminator>
  32. </resultMap>
  33. <!-- public Employee getEmpByIdStep(Integer id);-->
  34. <select id="getEmpByIdStep" resultMap="MyEmpDis">
  35. select * from employee where id=#{id}
  36. </select>

测试

  1. @Test
  2. public void test05() throws IOException{
  3. SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
  4. SqlSession sqlSession = sqlSessionFactory.openSession();
  5. try{
  6. EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
  7. Employee empByIdStep = mapper.getEmpByIdStep(1);
  8. System.out.println(empByIdStep.getLastName());
  9. System.out.println(empByIdStep.getDept());
  10. }finally{
  11. sqlSession.close();
  12. }
  13. }

运行效果

女生时:
在这里插入图片描述
男生时:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,122人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Mybatis-映射文件

    Mybatis-映射文件(二) Mybatis的真正强大在于它的映射语句,也是它的魔力所在。由于它的异常强大,映射器XML文件就显得相对简单。如果拿他跟具有相同功能的JD