JAVAEE close look at the framework 12-Mybatis multi-table operation lazy loading

MyBatis multi-table operation lazy loading

1. One-to-one operation:

<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. For many operations:

<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. Lazy loading

What is lazy loading

Initiate queries only when the data is actually used, and do not query when not in use. Load on demand (lazy loading)

What is loading immediately

Regardless of whether it is used or not, as soon as the method is called, the query is initiated immediately.

<!-- 在SqlMapConfig文件中,开启mybatis的懒加载机制 -->
<settings>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>
78 original articles published · Liked 30 · Visits 3631

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105276844