1. drop database if exists simple;
  2. create database simple;
  3.  
  4. use simple;
  5. drop table if exists sys_user;
  6. create table sys_user
  7. (
  8. id bigint not null auto_increment comment '用户ID',
  9. user_name varchar(50) comment '用户名',
  10. user_password varchar(50) comment '密码',
  11. user_email varchar(50) comment '邮箱',
  12. user_info text comment '简介',
  13. head_img blob comment '头像',
  14. create_time datetime comment '创建时间',
  15. primary key (id)
  16. );
  17. alter table sys_user comment '用户表';
  18.  
  19. drop table if exists sys_role;
  20. create table sys_role(
  21. id bigint not null auto_increment comment '角色ID',
  22. role_name varchar(50) comment '角色名',
  23. enabled int comment '有效标志',
  24. create_by bigint comment '创建人',
  25. create_time datetime comment '创建时间',
  26. primary key (id)
  27. );
  28. alter table sys_role comment '角色表';
  29.  
  30. drop table if exists sys_privilege;
  31. create table sys_privilege
  32. (
  33. id bigint not null auto_increment comment '权限ID',
  34. privilege_name varchar(50) comment '权限名称',
  35. privilege_url varchar(50) comment '权限URL',
  36. primary key (id)
  37. );
  38. alter table sys_privilege comment '权限表';
  39.  
  40. drop table if exists sys_user_role;
  41. create table sys_user_role
  42. (
  43. user_id bigint comment '用户ID',
  44. role_id bigint comment '角色ID'
  45. );
  46. alter table sys_user_role comment '用户角色关联表';
  47.  
  48. drop table if exists sys_role_privilege;
  49. create table sys_role_privilege
  50. (
  51. role_id bigint comment '用户ID',
  52. privilege_id bigint comment '角色ID'
  53. );
  54. alter table sys_role_privilege comment '角色权限关联表';

假如1个用户只能有1种角色sys_user和sys_role是通过sys_user_role一对一关联;

1.使用自动映射处理一对一关系;优点:当一定会使用到嵌套结果时使用。

  1.在SysUser.class model中增加SysRole的对象。

  1. private SysRole role;

  2.在查询的xml Mapper文件中对查询出的role属性写出对应的属性名称。

  1. <select id="selectUserAndById" resultType="test.model.SysUser">
  2. select
  3. u.id,
  4. u.user_name userName,
  5. u.user_password userPassword,
  6. u.user_email userEmail,
  7. u.create_time createTime,
  8. u.user_info userInfo,
  9. u.head_img headImg,
  10. r.id "role.id",
  11. r.role_name "role.roleName",
  12. r.enabled "role.enabled",
  13. r.create_by "role.createBy",
  14. r.create_time "role.createTime"
  15. from sys_user u inner join sys_user_role ur on u.id=ur.user_id
  16. inner join sys_role r on ur.user_id=r.id where u.id=#{id}
  17. </select>

2.使用resultMap配置一对一映射

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="test.dao.SysUserMapper">
  4. <resultMap id="BaseResultMap" type="test.model.SysUser">
  5. <!--
  6. WARNING - @mbggenerated
  7. This element is automatically generated by MyBatis Generator, do not modify.
  8. -->
  9. <id column="id" jdbcType="BIGINT" property="id" />
  10. <result column="user_name" jdbcType="VARCHAR" property="userName" />
  11. <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
  12. <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
  13. <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  14. <result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
  15. <result column="head_img" jdbcType="LONGVARBINARY" property="headImg" />
  16.  
  17. </resultMap>
  18.  
  19. <resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
  20. <!-- role相关属性 -->
  21. <result column="role_id" jdbcType="BIGINT" property="role.id" />
  22. <result column="role_name" jdbcType="VARCHAR" property="role.roleName" />
  23. <result column="enabled" jdbcType="INTEGER" property="role.enabled" />
  24. <result column="create_by" jdbcType="BIGINT" property="role.createBy" />
  25. <result column="role_create_time" jdbcType="TIMESTAMP" property="role.createTime" />
  26. </resultMap>

  27. <!-- 注意返回 resultMap="userRoleResultMap"-->
  28. <select id="selectUserAndById" resultMap="userRoleResultMap">
  29. select
  30. u.id,
  31. u.user_name,
  32. u.user_password,
  33. u.user_email,
  34. u.create_time,
  35. u.user_info,
  36. u.head_img,
  37. r.id role_id,
  38. r.role_name role_name,
  39. r.enabled enabled,
  40. r.create_by create_by,
  41. r.create_time role_create_time
  42. from sys_user u inner join sys_user_role ur on u.id=ur.user_id
  43. inner join sys_role r on ur.user_id=r.id where u.id=#{id}
  44. </select>
  45. </mapper>

3.使用resultMap的associaction标签配置一对一映射

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="test.dao.SysUserMapper">
  4. <resultMap id="BaseResultMap" type="test.model.SysUser">
  5. <!--
  6. WARNING - @mbggenerated
  7. This element is automatically generated by MyBatis Generator, do not modify.
  8. -->
  9. <id column="id" jdbcType="BIGINT" property="id" />
  10. <result column="user_name" jdbcType="VARCHAR" property="userName" />
  11. <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
  12. <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
  13. <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  14. <result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
  15. <result column="head_img" jdbcType="LONGVARBINARY" property="headImg" />
  16.  
  17. </resultMap>
  18.  
  19. <!-- 继承上面的UserResultMap -->
  20. <resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
  21. <!-- role相关属性 -->
  22. <!-- 对应的ResultMap在test.dao.SysRoleMapper这个命名控件中-->
  23. <association property="role" columnPrefix="role_" resultMap="test.dao.SysRoleMapper.BaseResultMap"></association>
  24. </resultMap>
  25.  
  26. <select id="selectUserAndById" resultMap="userRoleResultMap">
  27. select
  28. u.id,
  29. u.user_name,
  30. u.user_password,
  31. u.user_email,
  32. u.create_time,
  33. u.user_info,
  34. u.head_img,
  35. r.id role_id,
  36. r.role_name role_role_name,
  37. r.enabled role_enabled,
  38. r.create_by role_create_by,
  39. r.create_time role_create_time
  40. from sys_user u inner join sys_user_role ur on u.id=ur.user_id
  41. inner join sys_role r on ur.user_id=r.id where u.id=#{id}
  42. </select>
  43. <mapper/>
  1. <mapper namespace="test.dao.SysRoleMapper">
  2. <resultMap id="BaseResultMap" type="test.model.SysRole">
  3. <!--
  4. WARNING - @mbggenerated
  5. This element is automatically generated by MyBatis Generator, do not modify.
  6. -->
  7. <id column="id" jdbcType="BIGINT" property="id" />
  8. <result column="role_name" jdbcType="VARCHAR" property="roleName" />
  9. <result column="enabled" jdbcType="INTEGER" property="enabled" />
  10. <result column="create_by" jdbcType="BIGINT" property="createBy" />
  11. <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  12. </resultMap>
  13. </mapper>

4.association标签的嵌套查询 (子查询)

  1. fetchType="lazy";还需要在配置文件中加
  1. <settings>
  2. <setting name="logImpl" value="LOG4J"/>
    <setting name="aggressiveLazyLoading" value="false"/>
  3. </settings>
  1. <!-- SysUserMapper.xml -->
    <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="test.dao.SysUserMapper">
  4. <resultMap id="BaseResultMap" type="test.model.SysUser">
  5. <!--
  6. WARNING - @mbggenerated
  7. This element is automatically generated by MyBatis Generator, do not modify.
  8. -->
  9. <id column="id" jdbcType="BIGINT" property="id" />
  10. <result column="user_name" jdbcType="VARCHAR" property="userName" />
  11. <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
  12. <result column="user_email" jdbcType="VARCHAR" property="userEmail" />
  13. <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  14. <result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
  15. <result column="head_img" jdbcType="LONGVARBINARY" property="headImg" />
  16.  
  17. </resultMap>
  18.  
  19. <!-- 继承上面的UserResultMap -->
  20. <resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
  21. <!-- role相关属性 -->
  22. <!-- 对应的ResultMap在test.dao.SysRoleMapper这个命名控件中 注意这里没有resultMap="" -->
  23. <association property="role" column="{id=role_id}" fetchType="lazy" select="test.dao.SysRoleMapper.selectRoleById"></association>
  24. </resultMap>
  25.  
  26. <select id="selectUserAndById" resultMap="userRoleResultMap">
  27. select
  28. u.id,
  29. u.user_name,
  30. u.user_password,
  31. u.user_email,
  32. u.create_time,
  33. u.user_info,
  34. u.head_img,
  35. ur.role_id
  36. from sys_user u inner join sys_user_role ur on u.id=ur.user_id
  37. where u.id=#{id}
  38. </select>
  39. </mapper>
  1. <!--- RoleMapper.xml ->
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="test.dao.SysRoleMapper">
  5. <resultMap id="BaseResultMap" type="test.model.SysRole">
  6. <!--
  7. WARNING - @mbggenerated
  8. This element is automatically generated by MyBatis Generator, do not modify.
  9. -->
  10. <id column="id" jdbcType="BIGINT" property="id" />
  11. <result column="role_name" jdbcType="VARCHAR" property="roleName" />
  12. <result column="enabled" jdbcType="INTEGER" property="enabled" />
  13. <result column="create_by" jdbcType="BIGINT" property="createBy" />
  14. <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
  15. </resultMap>
  16.  
  17. <select id="selectRoleById" resultMap="BaseResultMap">
  18. select * from sys_role where id=#{id}
  19. </select>
  20. </mapper>

测试不能用debug看效果;

单元测试

  1. package com.watermelon.test;
  2.  
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.junit.Assert;
  5. import org.junit.Test;
  6.  
  7. import test.dao.SysUserMapper;
  8. import test.model.SysUser;
  9.  
  10. public class SysUserMappertest extends BaseMapperTest{
  11.  
  12. @Test
  13. public void testSelectUserAndById() {
  14. SqlSession sqlSession = getSqlSession();
  15. SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);
  16. SysUser user = sysUserMapper.selectUserAndById(1L);
  17. Assert.assertNotNull(user);
  18. System.out.println("调用user.getRole()");
  19. Assert.assertNotNull(user.getRole());
  20. }
  21. }

直接运行效果:

  1. DEBUG [main] - ==> Preparing: select u.id, u.user_name, u.user_password, u.user_email, u.create_time, u.user_info, u.head_img, ur.role_id from sys_user u inner join sys_user_role ur on u.id=ur.user_id where u.id=?
  2. DEBUG [main] - ==> Parameters: 1(Long)
  3. TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time, user_info, head_img, role_id
  4. TRACE [main] - <== Row: 1, admin, 123456, admin@mybats.tk, 2017-09-25 15:55:15.0, <<BLOB>>, <<BLOB>>, 1
  5. DEBUG [main] - <== Total: 1
  6. 调用user.getRole()
  7. DEBUG [main] - ==> Preparing: select * from sys_role where id=?
  8. DEBUG [main] - ==> Parameters: 1(Long)
  9. TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time
  10. TRACE [main] - <== Row: 1, 管理员, 1, 1, 2017-09-25 15:55:59.0
  11. DEBUG [main] - <== Total: 1

debug效果:

注:虽然这个方法已经满足了我们的要求,但是有些时候还是需要在触发某些方法时将所有的数据都加载进来。

可以调用对象的“equals,clone,hashCode,toString”.等方法。

  1. @Test
  2. public void testSelectUserAndById() {
  3. SqlSession sqlSession = getSqlSession();
  4. SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);
  5. SysUser user = sysUserMapper.selectUserAndById(1L);
  6. Assert.assertNotNull(user);
  7. // String s = "";
  8. // s.equals(null);
  9. //上面不行,必须是返回对象的方法
  10. user.equals(null);
  11. System.out.println("调用user.getRole()");
  12. Assert.assertNotNull(user.getRole());
  13. }

结果:

  1. DEBUG [main] - ==> Preparing: select u.id, u.user_name, u.user_password, u.user_email, u.create_time, u.user_info, u.head_img, ur.role_id from sys_user u inner join sys_user_role ur on u.id=ur.user_id where u.id=?
  2. DEBUG [main] - ==> Parameters: 1(Long)
  3. TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time, user_info, head_img, role_id
  4. TRACE [main] - <== Row: 1, admin, 123456, admin@mybats.tk, 2017-09-25 15:55:15.0, <<BLOB>>, <<BLOB>>, 1
  5. DEBUG [main] - <== Total: 1
  6. DEBUG [main] - ==> Preparing: select * from sys_role where id=?
  7. DEBUG [main] - ==> Parameters: 1(Long)
  8. TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time
  9. TRACE [main] - <== Row: 1, 管理员, 1, 1, 2017-09-25 15:55:59.0
  10. DEBUG [main] - <== Total: 1
  11. 调用user.getRole()

MyBatis高级查询 一对一映射的更多相关文章

  1. MyBatis高级查询

    -------------------------siwuxie095 MyBatis 高级查询 1.MyBatis 作为一个 ORM 框架,也对 SQL 的高级查询做了支持, MyBatis 高级查 ...

  2. MyBatis 高级查询环境准备(八)

    MyBatis 高级查询 之前在学习 Mapper XML 映射文件时,说到 resultMap 标记是 MyBatis 中最重要最强大也是最复杂的标记,而且还提到后面会详细介绍它的高级用法. 听到高 ...

  3. MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.1高级结果映射之一对一映射

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.2.4 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...

  4. MyBatis 高级查询之一对一查询(九)

    高级查询之一对一查询 查询条件:根据游戏角色ID,查询账号信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据角色ID查询账号信息 * @para ...

  5. Mybatis高级查询之一对一查询的四种方法

    目录 1. 一对一查询 1.1 一对一嵌套结果查询 1.2 使用resultMap配置一对一映射 1.3 使用resultMap的association标签配置一对一映射 1.4 associatio ...

  6. MyBatis 高级查询之一对多查询(十)

    高级查询之一对多查询 查询条件:根据游戏名称,查询游戏账号信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据游戏名查询游戏账号 * @param ...

  7. MyBatis 高级查询之多对多查询(十一)

    高级查询之多对多查询 查询条件:根据玩家名,查询游戏信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据玩家名查询游戏 * @param name ...

  8. Mybatis 高级查询的小整理

    高级查询的整理 // resutlType无法帮助我们自动的去完成映射,所以只有使用resultMap手动的进行映射 resultMap: type 结果集对应的数据类型 id 唯一标识,被引用的时候 ...

  9. MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.2高级结果映射之一对多映射

    jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.3.1 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...

随机推荐

  1. Vue.js 计算属性(computed)

    Vue.js 计算属性(computed) 如果在模板中使用一些复杂的表达式,会让模板显得过于繁重,且后期难以维护.对此,vue.js 提供了计算属性(computed),你可以把这些复杂的表达式写到 ...

  2. KMP瞎扯一下

    什么是KMP KMP俗称看毛片算法,是高效寻找匹配字串的一个算法 百度百科 KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现,因此人们称它为 ...

  3. python3.3+selenium

    1.查看C:\Python33\Scripts下已经有了easy_install.exe; 2.从这里下载pip tar.gz,并解压到C盘,https://pypi.python.org/pypi/ ...

  4. textbook references

    * math 1. Teubner-Taschenbuch der Mathematik * CFD

  5. 移动端禁止滑动的js处理方式

    下面是禁止移动端滑动事件的方式,慎用  document.querySelector('body').addEventListener('touchmove', function (ev) {     ...

  6. SqlServer2008必须开启哪些服务

    SQL Server 2008 大概有下面这些服务 SQL Active Directory Helper 服务支持与 Active Directory 的集成SQL Full-text Filter ...

  7. 【02】bootstrap起步

    起步 简要介绍 Bootstrap,以及如何下载.使用,还有基本模版和案例,等等. 下载 Bootstrap (当前版本 v3.3.5)提供以下几种方式帮你快速上手,每一种方式针对具有不同技能等级的开 ...

  8. Java MyBatis 插入数据库返回主键--insertSelective这样就不用每次到数据库里面查询了

    insertSelective---Java MyBatis 插入数据库返回主键--insertSelective这样就不用每次到数据库里面查询了 https://www.cnblogs.com/xi ...

  9. SQL to MongoDB Mapping Chart

    http://docs.mongodb.org/manual/reference/sql-comparison/ In addition to the charts that follow, you ...

  10. 常州模拟赛d7t1 亲戚

    分析:把题目换个方式理解,就是把各个点排成一列,并且指定了若干对的先后次序,问你有多少种序列满足要求. 显然是一道dp题,直接推出方程似乎有点点困难,那么先看看数据特点. 1.有一些点满足fi=0,那 ...