MyBatis高级查询 一对一映射
drop database if exists simple;
create database simple; use simple;
drop table if exists sys_user;
create table sys_user
(
id bigint not null auto_increment comment '用户ID',
user_name varchar(50) comment '用户名',
user_password varchar(50) comment '密码',
user_email varchar(50) comment '邮箱',
user_info text comment '简介',
head_img blob comment '头像',
create_time datetime comment '创建时间',
primary key (id)
);
alter table sys_user comment '用户表'; drop table if exists sys_role;
create table sys_role(
id bigint not null auto_increment comment '角色ID',
role_name varchar(50) comment '角色名',
enabled int comment '有效标志',
create_by bigint comment '创建人',
create_time datetime comment '创建时间',
primary key (id)
);
alter table sys_role comment '角色表'; drop table if exists sys_privilege;
create table sys_privilege
(
id bigint not null auto_increment comment '权限ID',
privilege_name varchar(50) comment '权限名称',
privilege_url varchar(50) comment '权限URL',
primary key (id)
);
alter table sys_privilege comment '权限表'; drop table if exists sys_user_role;
create table sys_user_role
(
user_id bigint comment '用户ID',
role_id bigint comment '角色ID'
);
alter table sys_user_role comment '用户角色关联表'; drop table if exists sys_role_privilege;
create table sys_role_privilege
(
role_id bigint comment '用户ID',
privilege_id bigint comment '角色ID'
);
alter table sys_role_privilege comment '角色权限关联表';



假如1个用户只能有1种角色sys_user和sys_role是通过sys_user_role一对一关联;
1.使用自动映射处理一对一关系;优点:当一定会使用到嵌套结果时使用。
1.在SysUser.class model中增加SysRole的对象。
private SysRole role;
2.在查询的xml Mapper文件中对查询出的role属性写出对应的属性名称。
<select id="selectUserAndById" resultType="test.model.SysUser">
select
u.id,
u.user_name userName,
u.user_password userPassword,
u.user_email userEmail,
u.create_time createTime,
u.user_info userInfo,
u.head_img headImg,
r.id "role.id",
r.role_name "role.roleName",
r.enabled "role.enabled",
r.create_by "role.createBy",
r.create_time "role.createTime"
from sys_user u inner join sys_user_role ur on u.id=ur.user_id
inner join sys_role r on ur.user_id=r.id where u.id=#{id}
</select>
2.使用resultMap配置一对一映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.SysUserMapper">
<resultMap id="BaseResultMap" type="test.model.SysUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_password" jdbcType="VARCHAR" property="userPassword" />
<result column="user_email" jdbcType="VARCHAR" property="userEmail" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
<result column="head_img" jdbcType="LONGVARBINARY" property="headImg" /> </resultMap> <resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
<!-- role相关属性 -->
<result column="role_id" jdbcType="BIGINT" property="role.id" />
<result column="role_name" jdbcType="VARCHAR" property="role.roleName" />
<result column="enabled" jdbcType="INTEGER" property="role.enabled" />
<result column="create_by" jdbcType="BIGINT" property="role.createBy" />
<result column="role_create_time" jdbcType="TIMESTAMP" property="role.createTime" />
</resultMap>
<!-- 注意返回 resultMap="userRoleResultMap"-->
<select id="selectUserAndById" resultMap="userRoleResultMap">
select
u.id,
u.user_name,
u.user_password,
u.user_email,
u.create_time,
u.user_info,
u.head_img,
r.id role_id,
r.role_name role_name,
r.enabled enabled,
r.create_by create_by,
r.create_time role_create_time
from sys_user u inner join sys_user_role ur on u.id=ur.user_id
inner join sys_role r on ur.user_id=r.id where u.id=#{id}
</select>
</mapper>
3.使用resultMap的associaction标签配置一对一映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.SysUserMapper">
<resultMap id="BaseResultMap" type="test.model.SysUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_password" jdbcType="VARCHAR" property="userPassword" />
<result column="user_email" jdbcType="VARCHAR" property="userEmail" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
<result column="head_img" jdbcType="LONGVARBINARY" property="headImg" /> </resultMap> <!-- 继承上面的UserResultMap -->
<resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
<!-- role相关属性 -->
<!-- 对应的ResultMap在test.dao.SysRoleMapper这个命名控件中-->
<association property="role" columnPrefix="role_" resultMap="test.dao.SysRoleMapper.BaseResultMap"></association>
</resultMap> <select id="selectUserAndById" resultMap="userRoleResultMap">
select
u.id,
u.user_name,
u.user_password,
u.user_email,
u.create_time,
u.user_info,
u.head_img,
r.id role_id,
r.role_name role_role_name,
r.enabled role_enabled,
r.create_by role_create_by,
r.create_time role_create_time
from sys_user u inner join sys_user_role ur on u.id=ur.user_id
inner join sys_role r on ur.user_id=r.id where u.id=#{id}
</select>
<mapper/>
<mapper namespace="test.dao.SysRoleMapper">
<resultMap id="BaseResultMap" type="test.model.SysRole">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="role_name" jdbcType="VARCHAR" property="roleName" />
<result column="enabled" jdbcType="INTEGER" property="enabled" />
<result column="create_by" jdbcType="BIGINT" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
</mapper>
4.association标签的嵌套查询 (子查询)
fetchType="lazy";还需要在配置文件中加
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!-- SysUserMapper.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.SysUserMapper">
<resultMap id="BaseResultMap" type="test.model.SysUser">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_password" jdbcType="VARCHAR" property="userPassword" />
<result column="user_email" jdbcType="VARCHAR" property="userEmail" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="user_info" jdbcType="LONGVARCHAR" property="userInfo" />
<result column="head_img" jdbcType="LONGVARBINARY" property="headImg" /> </resultMap> <!-- 继承上面的UserResultMap -->
<resultMap type="test.model.SysUser" id="userRoleResultMap" extends="BaseResultMap">
<!-- role相关属性 -->
<!-- 对应的ResultMap在test.dao.SysRoleMapper这个命名控件中 注意这里没有resultMap="" -->
<association property="role" column="{id=role_id}" fetchType="lazy" select="test.dao.SysRoleMapper.selectRoleById"></association>
</resultMap> <select id="selectUserAndById" resultMap="userRoleResultMap">
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=#{id}
</select>
</mapper>
<!--- RoleMapper.xml ->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test.dao.SysRoleMapper">
<resultMap id="BaseResultMap" type="test.model.SysRole">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="role_name" jdbcType="VARCHAR" property="roleName" />
<result column="enabled" jdbcType="INTEGER" property="enabled" />
<result column="create_by" jdbcType="BIGINT" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap> <select id="selectRoleById" resultMap="BaseResultMap">
select * from sys_role where id=#{id}
</select>
</mapper>
测试不能用debug看效果;
单元测试
package com.watermelon.test; import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test; import test.dao.SysUserMapper;
import test.model.SysUser; public class SysUserMappertest extends BaseMapperTest{ @Test
public void testSelectUserAndById() {
SqlSession sqlSession = getSqlSession();
SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);
SysUser user = sysUserMapper.selectUserAndById(1L);
Assert.assertNotNull(user);
System.out.println("调用user.getRole()");
Assert.assertNotNull(user.getRole());
}
}
直接运行效果:
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=?
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time, user_info, head_img, role_id
TRACE [main] - <== Row: 1, admin, 123456, admin@mybats.tk, 2017-09-25 15:55:15.0, <<BLOB>>, <<BLOB>>, 1
DEBUG [main] - <== Total: 1
调用user.getRole()
DEBUG [main] - ==> Preparing: select * from sys_role where id=?
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time
TRACE [main] - <== Row: 1, 管理员, 1, 1, 2017-09-25 15:55:59.0
DEBUG [main] - <== Total: 1
debug效果:

注:虽然这个方法已经满足了我们的要求,但是有些时候还是需要在触发某些方法时将所有的数据都加载进来。
可以调用对象的“equals,clone,hashCode,toString”.等方法。
@Test
public void testSelectUserAndById() {
SqlSession sqlSession = getSqlSession();
SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);
SysUser user = sysUserMapper.selectUserAndById(1L);
Assert.assertNotNull(user);
// String s = "";
// s.equals(null);
//上面不行,必须是返回对象的方法
user.equals(null);
System.out.println("调用user.getRole()");
Assert.assertNotNull(user.getRole());
}
结果:
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=?
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <== Columns: id, user_name, user_password, user_email, create_time, user_info, head_img, role_id
TRACE [main] - <== Row: 1, admin, 123456, admin@mybats.tk, 2017-09-25 15:55:15.0, <<BLOB>>, <<BLOB>>, 1
DEBUG [main] - <== Total: 1
DEBUG [main] - ==> Preparing: select * from sys_role where id=?
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time
TRACE [main] - <== Row: 1, 管理员, 1, 1, 2017-09-25 15:55:59.0
DEBUG [main] - <== Total: 1
调用user.getRole()
MyBatis高级查询 一对一映射的更多相关文章
- MyBatis高级查询
-------------------------siwuxie095 MyBatis 高级查询 1.MyBatis 作为一个 ORM 框架,也对 SQL 的高级查询做了支持, MyBatis 高级查 ...
- MyBatis 高级查询环境准备(八)
MyBatis 高级查询 之前在学习 Mapper XML 映射文件时,说到 resultMap 标记是 MyBatis 中最重要最强大也是最复杂的标记,而且还提到后面会详细介绍它的高级用法. 听到高 ...
- MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.1高级结果映射之一对一映射
jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.2.4 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...
- MyBatis 高级查询之一对一查询(九)
高级查询之一对一查询 查询条件:根据游戏角色ID,查询账号信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据角色ID查询账号信息 * @para ...
- Mybatis高级查询之一对一查询的四种方法
目录 1. 一对一查询 1.1 一对一嵌套结果查询 1.2 使用resultMap配置一对一映射 1.3 使用resultMap的association标签配置一对一映射 1.4 associatio ...
- MyBatis 高级查询之一对多查询(十)
高级查询之一对多查询 查询条件:根据游戏名称,查询游戏账号信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据游戏名查询游戏账号 * @param ...
- MyBatis 高级查询之多对多查询(十一)
高级查询之多对多查询 查询条件:根据玩家名,查询游戏信息 我们在之前创建的映射器接口 GameMapper.java 中添加接口方法,如下: /** * 根据玩家名查询游戏 * @param name ...
- Mybatis 高级查询的小整理
高级查询的整理 // resutlType无法帮助我们自动的去完成映射,所以只有使用resultMap手动的进行映射 resultMap: type 结果集对应的数据类型 id 唯一标识,被引用的时候 ...
- MyBatis从入门到精通(第6章):MyBatis 高级查询->6.1.2高级结果映射之一对多映射
jdk1.8.MyBatis3.4.6.MySQL数据库5.6.45.IntelliJ IDEA 2019.3.1 本章主要包含的内容为 MyBatis 的高级结果映射,主要处理数据库一对一.一对多的 ...
随机推荐
- spring 中属性scope 的prototype(有状态)和singleton(无状态)
默认情况下,从bean工厂所取得的实例为Singleton(bean的singleton属性) Singleton: Spring容器只存在一个共享的bean实例, 默认的配置. Prototype: ...
- Linux 源码
https://elixir.bootlin.com/linux/latest/source
- 深入分析同步工具类之CountDownLatch
概览: CountDownLatch又称闭锁,其作用是让一个或者多个线程挂起,直到其他的线程执行完后恢复挂起的线程,使其继续执行.内部维护着一个静态内部类Sync,该类继承AbstractQueued ...
- java用递归输出目录结构
package com.janson.day20180827; import java.io.File; public class TestTreeStructureDirectory { publi ...
- Oracle 回滚(ROLLBACK)和撤销(UNDO)
一.回滚(ROLLBACK)和撤销(UNDO) 回滚和前滚是保证Oracle数据库中的数据处于一致性状态的重要手段. 在9i版本以前 Oracle使用数据库中的回滚段来实现未提交数据或因系统故障导致实 ...
- 入门系列(一) 微信小程序简介
一.简介 1.目录结构 首先,我们使用微信公众平台提供的开发者工具,创建一个简单的小程序项目,观察项目的目录结构 不难看出,一个典型的微信小程序,通常包含一个描述整体的主体部分,以及一个描述页面的 p ...
- 09.C语言:预处理(宏定义)、字节序、地址对齐
一.预处理 预处理 gcc -E Hello.c -o hello.i 编译 gcc -S hello.i -o hello.s 汇编 gcc -c hello.s -o hello.o 链接 gcc ...
- 【05】JSON笔记
[05]笔记 尽管有许多宣传关于 XML 如何拥有跨平台,跨语言的优势,然而,除非应用于 Web Services,否则,在普通的 Web 应用中,开发者经常为 XML 的解析伤透 ...
- nyoj 108 士兵杀敌(一)
士兵杀敌(一) 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的. 小工是南将军手下的军师,南将军现在 ...
- [luoguP1879] [USACO06NOV]玉米田Corn Fields(DP)
传送门 说要统计方案,感觉就是个 Σ 而矩阵中只有 01 ,可以用二进制表示 这样,预处理出每一个每一行所有可能的状态 s 然后初始化第一行所有状态的方案数为 1 f[i][j] = Σf[i - 1 ...