延迟加载/懒加载
在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>