7.延迟加载/懒加载

延迟加载/懒加载

在mybatis的配置中存在一对一 或一对多映射 关系时,可以使用延迟加载
先只查询常用的一个表的信息,然后有需要的时候,再去执行查另一个表的操作

步骤:

1、在配置文件中,设置允许进行懒加载
在mybatis-config.xml文件中的<settings></settings>标签中,添加配置:

<!-- 设置允许延迟加载  true:允许,
false:默认值,不进行懒加载 
-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 按需加载:false -->
<setting name="aggressiveLazyLoading" value="false"/>

2、添加:延迟加载需要的jar
在mybatis-config.xml文件中的<settings></settings>标签中,添加配置:可以在控制台输出sql语句

<!-- 配置log4日志 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>

3、使用延迟加载查询的SQL,不能使用连接查询 (切记!!!)
4、先编写查询角色信息的方法:参数角色编号
UserDao 接口
UserMapper.xml 查询的SQL
UserRoleDao 接口
UserRoleMapper.xml 查询的SQL

UserDao.java

	//延迟加载,查角色
	public List<User> getAllUsersLazy();

UserMapper.xml

 <!-- 延迟加载
 1.不能进行表连接查询
 2.一定要配置映射结果resultMap
  -->
 <!-- 配置延迟加载的resultMap -->
 <resultMap type="User" id="userMap4">
 	<id property="id" column="id"></id>
 	<result property="userCode" column="userCode"></result>
 	<result property="userName" column="userName"></result>
 	<!-- 延迟加载,通过column=""来传参 -->
 	<association property="userRole2" javaType="UserRole"
 	select="cn.qf.smbms.dao.UserRoleDao.getUserRoleById"
 	column="UserRole"></association>
 </resultMap>
 <select id="getAllUsersLazy" resultMap="userMap4">
 	<!-- 只查询smbms_user一个表里的信息 -->
 	select id,userCode,userName,userRole,address,phone
 	from smbms_user
 </select>

UserRoleDao

//根据用户角色获取角色信息
public List<UserRole> getUserRoleById(int id);

UserRoleMapper.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="cn.qf.smbms.dao.UserRoleDao">
	<!-- 启用二级缓存 -->	
	<cache></cache>
	<select id="getUserRoleById" parameterType="int" resultType="UserRole">
		select id,roleCode,roleName
		from smbms_role
		where id=#{id}
	</select>
</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值