mybatis延迟加载的实现
1.关于延迟加载
(1)延迟加载也叫懒加载,根据需求加载数据,先加载主要显示的数据,如果需要关联的数据显示,再加载关联的数据显示
2.为什么使用延迟加载
(1)假设场景:用户表和订单表,用户表有多个用户,每个用户有多个订单, 某些时候,我们需要同时查看用户信息和用户的订单信息,这个时候用户的信息和订单的信息都需要显示。但如果我们只查看订单列表,就没必要把用户信息和用户的订单的数据全部查询出来,只显示订单信息就够了。如果想看订单详情,这时候需要显示订单的用户信息,再来加载订单的用户数据。那这个时候很明显 就需要用到延迟加载 (2)好处就是:避免资源浪费,提升查询速度
3.如何实现
(1)在sqlMapConfig配置文件中加入以下节点:
<settings>
<setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>
lazyLoadingEnabled 这个是开启懒加载的全局配置 aggressiveLazyLoading 这个属性必须改为false 否则不生效
(2) 1) 将原始的关联查询代码改为单表查询 原始sql语句
<select id="findUserAndOrderResultMap" resultMap="orderUserMap"> SELECT orders.id, orders.number, orders.createtime, user.id userId, user.username, user.birthday, user.sex, user.address FROM orders,USER WHERE orders.user_id = user.id </select>
更改后sql语句
<select id="findUserAndOrderResultMap" resultMap="orderUserMap"> SELECT * FROM orders </select>
2) 更改关联查询的resultMap内的映射association节点加入懒加载需要的查询条件 和sql语句statementId 原始resultMap映射
<resultMap type="orders" id="orderUserMap"> <id column="id" property="id"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <!-- association节点标明唯一关系映射 --> <association property="user" javaType="user"> <id column="userId" property="id"/> <result column="username" property="username"/> <result column="birthday" property="birthday"/> <result column="sex" property="sex"/> <result column="address" property="address"/> </association> </resultMap>
更改后的resultMap映射
<resultMap type="orders" id="orderUserMap"> <id column="id" property="id"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <!-- association节点标明唯一关系映射 --> <association property="user" javaType="user" column="user_id" select="findUserById"> </association> </resultMap>
3) 添加根据id查询用户的sql语句statement
<select id="findUserById" parameterType="int" resultType="user"> select * from user where id = #{id} </select>
##4.效果演示 查询订单信息输出
List<Orders> list = userMapper.findOrderAndUser(); for(Orders orders:list){ System.out.println(orders.getNumber()); }
运行测试方法控制台只会输出一条sql语句查询所有订单 00:02:27,127 DEBUG findOrderAndUser:139 - > Preparing: SELECT * FROM orders 00:02:27,166 DEBUG findOrderAndUser:139 - ==> Parameters: 00:02:27,280 DEBUG findOrderAndUser:139 - < Total: 3 如果在订单内部获取用户,才会又输出一条根据订单的用户id查询用户的sql语句
List<Orders> list = userMapper.findOrderAndUser(); for(Orders orders:list){ System.out.println(orders.getNumber()); System.out.println(orders.getUser()); }
00:09:22,927 DEBUG findOrderAndUser:139 - > Preparing: SELECT * FROM orders 00:09:22,964 DEBUG findOrderAndUser:139 - ==> Parameters: 00:09:23,078 DEBUG findOrderAndUser:139 - < Total: 3 1000010 00:09:23,079 DEBUG findUserById:139 - > Preparing: select * from user where id = ? 00:09:23,079 DEBUG findUserById:139 - ==> Parameters: 1(Integer) 00:09:23,081 DEBUG findUserById:139 - < Total: 1 User [id=1, username=王五, sex=男, birthday=null, address=null]