MyBatis多表操作延迟加载
1. 对一操作:
<resultMap id="orderMap" type="order">
<result property="id" column="id"></result>
<result property="ordertime" column="ordertime"></result>
<result property="total" column="total"></result>
<!--
当查询order的时候,mybatis会把查询结果中的uid列中的数据,一个一个拿出来,然后调用 UserMapper.findById方法,查询数据,并把查询到数据,封装到order对象的user属性中。
-->
<association property="user" javaType="user"
select="com.ittest.dao.UserMapper.findById" column="uid">
</association>
</resultMap>
<!-- 获取所有的order -->
<select id="findAll" resultMap="orderMap">
SELECT * FROM orders
</select>
<!-- 根据用户id,查询对应的所有的订单 -->
<select id="findByUid" resultType="order">
SELECT * FROM orders WHERE uid = #{uid}
</select>
2. 对多操作:
<resultMap id="userMap" type="user">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<result property="password" column="password"></result>
<result property="birthday" column="birthday"></result>
<!--
当查询user的时候,mybatis会把查询结果中的id列中的数据,一个一个拿出来,然后调用 OrderMapper.findByUid方法,查询数据,并把查询到数据,封装到user对象的orders属性中。
-->
<collection property="orders" ofType="order"
select="com.ittest.dao.OrderMapper.findByUid" column="id">
</collection>
</resultMap>
<!-- 获取所有用户 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
<!-- 根据用户id,获取用户 -->
<select id="findById" resultType="user">
select * from user where id = #{id}
</select>
3. 延迟加载
什么是延迟加载
在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)
什么是立即加载
不管用不用,只要一调用方法,马上发起查询。
<!-- 在SqlMapConfig文件中,开启mybatis的懒加载机制 -->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>