前面一篇文章,介绍了多表查询,在实际使用中,我们会经常性的涉及到多表联合查询,但是有时候,并不会立即用到所有的查询结果。
针对这样一种情况,延迟加载这一种机制就出现了,延迟加载(懒加载)顾名思义,就是对某种信息推迟加载,这样的技术也就帮助我们实现了 “按需查询” 的机制,在一对多,或者多对多的情况下。
1.何为延迟加载?
在真正的使用数据时才发起查询,不用的时候不查。按需加载(懒加载)。
既然提到了延迟加载,当然顺便提一句立即加载,它的含义就是不管是否用户需要,一调用,则马上查询,这种方式,适合与多对一,或者一对一的情况下。
fetchType="lazy"局部延迟加载,写在 <collection>标签里面
全局开启延迟加载,写在resources文件夹下的mybatis-config.xml文件里面:
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
2.使用延迟加载
以一对多查询为例
2.1建立数据库表
首先,配置基本的环境,然后我们首先在数据库准备两张表
account表:
user表:
2.2创建实体类
account.java
private Integer id;
private Integer uid;
private Double money;
//一方
private User user;
user.java
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//多方
private List<Account> accountList;
2.3创建xml文件
UserMapper.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="com.by.mapper.UserMapper">
<resultMap id="getUserByIdResultMap" type="com.by.pojo.User">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!--
property="accountList":pojo的属性
ofType="account":集合的泛型
select="com.by.mapper.AccountMapper.selectAccountByUid":要调用的select标签的id
column="id":传递的参数
fetchType="lazy":局部开启延迟加载
-->
<collection property="accountList"
ofType="com.by.pojo.Account"
select="com.by.mapper.AccountMapper.selectAccountByUid"
column="id"
fetchType="lazy">
</collection>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="getUserByIdResultMap">
SELECT * FROM user WHERE id=#{id}
</select>
</mapper>
① property:pojo的属性
②ofType:集合的泛型
③select:要调用的select标签的id
④column:传递的参数
⑤fetchType:局部开启延迟加载
AccountMapper.xml,select的id名称和UserMapper.xml中collection的select标签保持一致:
<?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="com.by.mapper.AccountMapper">
<select id="selectAccountByUid" parameterType="int" resultType="com.by.pojo.Account">
SELECT * FROM account WHERE uid = #{uid}
</select>
</mapper>
2.4建立接口
UserMapper接口
public interface UserMapper {
User getUserById(Integer id);
}
建立 AccountMapper接口,可不写selectAccountByUid函数
public interface AccountMapper {
}
2.5测试类的编写
@Test
public void getUserById(){
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(41);
System.out.println(user.getUsername());
List<Account> accountList = user.getAccountList();
for (Account account : accountList) {
System.out.println(account);
}
}
加载上面getUserById的语句时的结果:
全部加载时的结果为: