Mybatis应用学习(4)——延迟加载

1. 经过resultMap实现延迟加载

    1. 经过resultMap中的子标签association和collection能够实现一对1、一对多、多对多查询,经过还能够经过这两标签实现延迟加载java

    2. 应用场景:好比查询NoteBook相关数据并关联查询User信息,若是暂时只须要NoteBook数据而不须要User,那么仅查询NoteBook信息便可,若是须要User信息时,在关联查询User。mybatis

    3. 延迟加载:先从单表查询所须要的数据,若是须要关联表中的数据,那么就进行关联查询,能够提升性能,由于单表查询比多表联合查询要快。app

    4. 经过mybatis的启动配置文件开启延迟加载:经过settings标签来开启延迟加载,添加以下标签后便可进行延迟加载性能

<settings>
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

    5. 经过association标签实现:spa

<?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="dao.NoteBookDao">

	<!-- 先进行单表查询,而后经过 resultMap实现延迟加载,
	完整的SQL语句能够写为
	select *,
	(select cn_user_name from cn_user where cn_user_id=cn_notebook.cn_user_id) cn_user_name,
	(select cn_user_password from cn_user where cn_user_id=cn_notebook.cn_user_id) cn_user_password,
	from cn_notebook where cn_notebook_id=#{cn_notebook_id} 
	resultMap中的association就至关于括号内的子查询语句
	-->
	<select id="lazyLoadingQuery" parameterType="string" resultMap="lazyLoading">
		select * from cn_notebook where cn_notebook_id=#{cn_notebook_id}
	</select>
	<!-- 经过 resultMap实现延迟加载-->
	<resultMap type="entity.UserAndNoteBook2" id="lazyLoading">
		<id column="cn_notebook_id" property="cn_notebook_id"/>
		<result column="cn_user_id" property="cn_user_id"/>
		<result column="cn_notebook_type_id" property="cn_notebook_type_id"/>
		<result column="cn_notebook_name" property="cn_notebook_name"/>
		<result column="cn_notebook_desc" property="cn_notebook_desc"/>
		<result column="cn_notebook_createtime" property="cn_notebook_createtime"/>
		<!-- 对关联查询用户信息进行延迟加载,主要经过下面两个属性实现
		select:指定要延迟执行的SQL语句的id,能够写当前Mapper映射文件中的SQL也能够写其余Mapper映射文件中的
		column:指定将Notebook表中与User表创建关联关系的列,经过该列来进行关联查询
		 -->
		<association property="user" javaType="entity.User" select="lazyLoadingQueryUser" column="cn_user_id">

		</association>				
	</resultMap>
	<!-- 定义延迟执行的SQL语句 -->
	<select id="lazyLoadingQueryUser" parameterType="string" resultType="entity.User">
		select * from cn_user where cn_user_id=#{cn_user_id}
	</select>
</mapper>

    6. 对于collection子标签也是一样的用法。code

    7. 实际上,不须要resultMap标签,只须要在Mapper映射文件中定义两个SQL语句,分别是xml

<select id="lazyLoadingQuery" parameterType="string" resultType="entity.NoteBook">
		select * from cn_notebook where cn_notebook_id=#{cn_notebook_id}
	</select>
	<select id="lazyLoadingQueryUser" parameterType="string" resultType="entity.User">
		select * from cn_user where cn_user_id=#{cn_user_id}
	</select>

    在Java代码中,首先经过lazyLoadingQuery对应的Mapper接口方法,查询获得NoteBook表对应的NoteBook对象,而后从该对象中取得cn_user_id属性的值,将该值做为参数lazyLoadingQueryUser对应的Mapper接口方法的参数,就能够查询获得对应的User数据对象

相关文章
相关标签/搜索