九、MyBatis的延迟加载

发布时间:2023年12月29日

9.1什么是延迟加载

????????延迟加载是一种技术,它允许在真正需要数据的时候才进行加载,而不是一开始就加载所有数据。这种技术可以提高应用程序的性能,因为它可以减少数据库查询的次数,降低网络和数据库的负载。在MyBatis中,延迟加载可以通过多种方式实现,例如使用<association><collection>元素或实现ResultHandler接口来自定义结果集的处理方式。

9.2mapper

public interface UserDao {
? ? public List<User> findAll();
}

<?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.dao.UserDao">
? ? <resultMap type="User" id="findAllResultMap">
? ? ? ? <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:属性名
? ? ? ? ? ofType:泛型
? ? ? ? ? select: 要调用的 select 映射的 id
? ? ? ? ? column : 传递给 select 映射的参数
? ? ? ? ? fetchType="lazy":懒加载,默认情况下是没有开启延迟加载的,局部配置
? ? ? ? ?-->
? ? ? ? <collection property="accounts" ofType="Account" fetchType="lazy"
? ? ? ? ? ? ? ? ? ? select="com.by.dao.AccountDao.findAccountById" column="id">?? ?
? ? ? ? </collection>
? ? </resultMap>

? ? <select id="findAll" resultMap="findAllResultMap">
? ? ? select * from user
? ? </select>
</mapper>

<?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.dao.AccountDao">
? ? <select id="findAccountById" resultType="account">
? ? ? ? select * from account where uid = #{id}
? ? </select>
</mapper>?

9.3全局开启懒加载

? ? <!-- 全局配置延迟加载策略 -->
? ? <settings>
? ? ? ? <!-- ?打开延迟加载的开关 ?-->
? ? ? ? <setting name="lazyLoadingEnabled" value="true"/>
? ? </settings>?

9.4测试?

<br class="Apple-interchange-newline"><div></div>

 
 
 ? ?@Test
 ? ?public void testFindAll() {
 ? ? ? ?UserDao userDao = sqlSession.getMapper(UserDao.class);
 ? ? ? ?List<User> userList = userDao.findAll();
 ? ? ? ?for(User user : userList){
 ? ? ? ? ? ?System.out.println(user.getUsername());//不查询account
 ? ? ? ? ? ?System.out.println(user.getAccounts());//查询account
 ? ? ?  }
 ?  }

?

文章来源:https://blog.csdn.net/wasd2051678946/article/details/135207968
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。