代码演示

图:from tuser、from role、from torde 的状态流转。

图:from torde、from tuser、from role 的状态流转。

图:from tuser、from torde、from role 的状态流转。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 懒加载机制 
按需加载查询数据,是优化数据库的方法。比如查询一个结果集,但是只会用到其中一个结果,那么懒加载就只会查询那个使用的结果,其他结果不会查询

1.全局文件中开启lazy机制
2.使用懒加载机制 - 必须使用resultMap
3.每个查询都要分开
-->

<resultMap type="user" id="userRoleOrdersLazyMap" autoMapping="true">

<!-- lazy查询 select="selectUserRole" column="roleId" -->
<association property="role" javaType="Role"
select="selectUserRole" column="roleId">
</association>

<collection property="orders" javaType="list" ofType="Order"
select="selectUserOrders" column="userId">
</collection>
</resultMap>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--查询也会分成3部分,每一步前后相接,对应上述的resultMap中的select-->
<select id="queryUserRoleOrdersByLazy" parameterType="int" resultMap="userRoleOrdersLazyMap">
select u.userId, u.userCode, u.name, u.roleId
from tuser u
where u.userId = #{value}
</select>

<select id="selectUserRole" resultType="role">
select roleId,roleName
from role
where roleId=#{roleId}
</select>

<select id="selectUserOrders" resultType="order">
select * (*应写全字段)
from torder
where userId=#{userId}
</select>