在使用associateion标签的嵌套查询中,一般嵌套查询常用的属性如下:
select:另一个映射查询的id,Mybatis会额外执行这个查询获取嵌套对象的结果。
column:列名(别名),将主查询中列的结果作为嵌套查询的参数,配置方式如 column={prop1=col1,prop2=col2},其中prop1和prop2将作为嵌套查询的参数。
fetchType:数据集在方式,可选lazy和eager,分别为延迟加载和积极加载,这个配置会覆盖全局的lazyLoadingEnabled配置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.chapter3.UserMapper">
<resultMap id="userMap" type="com.mybatis.chapter3.SysUser">
<id property="userName" column="user_name"/>
<result property="userName" column = "user_name"/>
<result property="userPassword" column = "user_password"/>
<result property="userEmail" column = "user_email"/>
<result property="userInfo" column = "user_info"/>
<result property="headImg" column = "head_img" jdbcType="BLOB"/>
<result property="create_time" column = "create_time" jdbcType="TIMESTAMP"/>
</resultMap>
<resultMap id="roleMap" type="com.mybatis.chapter3.SysRole">
<id property="id" column="id"/>
<result property="role_Name" column = "role_Name"/>
<result property="enabled" column = "enabled"/>
<result property="create_by" column = "create_by"/>
<result property="create_time" column = "create_time" jdbcType="TIMESTAMP"/>
</resultMap>
<!--id=role_id这句话的意思是将role_id赋值给id,作为selectRolebyId中的id条件-->
<resultMap id="userRoleMapSelect" extends="userMap" type="com.mybatis.chapter3.SysUser">
<association property="role" column="{id=role_id}" select="com.mybatis.chapter3.UserMapper.selectRolebyId"/>
</resultMap>
<select id="selectRolebyId" resultMap="roleMap">
select * from sys_role where id=#{id}
</select>
<select id="selectUserAndRoleByIdSelect" resultMap="userRoleMapSelect">
select
u.id,
u.user_name,
u.user_password,
u.user_email,
u.user_info,
u.head_img,
u.create_time,
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>
注意可用的参数是通过上面的column="{id=role_id}"进行配置的,因此在嵌套的sql中只能使用#{id}参数,当需要多个参数的时候,可以配置多个,使用,逗号可开即可,例如column="{id=role_id,name=role_name}"。
看一下关系联系图
但是出现的问题是,如果我们需要考虑到是否一定会用到呢?如果查询了并没有遇到那我们应该去优化代码?
我们需要了解到
1.使用fetchType="lazy"实现延迟加载,解决N+1的问题
2.将Mybatis中的全局配置中的setiting标签内的aggressiveLazyLoading中的value=false。