mybatis懒加载机制
需要查询关联信息时,使用Mybatis懒加载特性可有效的减少数据库压力,首次查询只查询主表信息,关联表的信息在用户获取时再加载。
Mybatis一对一关联的association和一对多的collection可以实现懒加载。懒加载时要使用resultMap,不能使用resultType。
1、在mybatis的全局配置中开启延迟加载功能
- Mybatis默认没有打开懒加载配置,需要在mybatis全局配置文件.xml中通过settings配置lazyLoadingEnabled、aggressiveLazyLoading(按需加载)来开启懒加载。
<settings>
<!-- dept_id转换为驼峰命名法deptId -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
2、*mapper.xml文件
注意在resultMap中配置名称可能比较绕,一般问题会出现在这。
association标签
<resultMap type="User" id="userMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="oper" column="oper"/>
<!-- property表示java实体中属性的名称,javaType表示属性的类型,column表示在查询结果中的列,selecr表示要执行的sql语句 fetchType表示取消延迟加载 -->
<association property="dept" javaType="Dept" column="dept_id" select="findDeptLazy" fetchType="eager" >
<id property="id" column="id"/>
<result property="deptName" column="dept_name"/>
<result property="deptDesc" column="dept_desc"/>
</association>
</resultMap>
<select id="findUserDeptLazy" parameterType="int" resultMap="userMap">
SELECT id ,name,sex,age,oper,dept_id
FROM t_user
WHERE id = #{id}
</select>
<select id="findDeptLazy" resultType="Dept">
SELECT id,dept_name,dept_desc
FROM t_dept
WHERE id = #{id}
</select>
collection标签
<!-- 懒加载 -->
<resultMap type="Dept" id="deptMapLazy">
<!-- 主键 -->
<id property="id" column="id"/>
<result property="deptName" column="dept_name"/>
<result property="deptDesc" column="dept_desc"/>
<!-- property表示java实体类中属性的名称,javaType表示属性的类型,ofType表示泛型,column表示应用查询的某列 select表示需要执行的sql语句 fetchType表示是否开启延迟加载eager取消延迟加载,lazy开启延迟加载,默认开启 -->
<collection property="userlist" javaType="ArrayList" ofType="User" column="id" select="fingUserList" fetchType="eager">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="oper" column="oper"/>
</collection>
</resultMap>
<select id="findDpetByIdLazy" parameterType="int" resultMap="deptMapLazy">
SELECT id,dept_name,dept_desc
from t_dept
where id = #{id}
</select>
<select id="fingUserList" resultType="User">
select id,name,sex,age,oper,dept_id
from t_user
where dept_id = #{dept_id}
</select>