前篇學習了多表查詢,能夠滿足我們在複雜的場景下的查詢,但不可否認的是,單表查詢在數據庫查詢的性能上是要優於多表查詢的。
因此,如果單表查詢可以滿足我們的需求,我們就應該查詢單表,當需要關聯多表信息的時候,再進行關聯查詢,這就是一個延遲加載的策略。
延遲加載的啓動配置
我們需要在主配置文件中<setting>
中配置lazyLoadingEnabled
和aggressiveLazyLoading
兩個屬性
<settings>
<!--開啓mybatis支持延遲加載-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--false,每個延遲加載屬性會按需加載,在 3.4.1 及之前的版本中默認爲 true-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
【一對一關係延遲加載】
<!-- com.itheima.dao.IAccountDao -->
<mapper namespace="com.itheima.dao.IAccountDao">
<!--定義封裝account和user的resultmap-->
<resultMap id="accountUserMap" type="account">
<!--account對象的封裝-->
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--一對一的關係映射,配置封裝user-->
<!--
select屬性指定的內容:查詢用戶的唯一標識.即延遲加載執行的sql所在的statement的id
column屬性指定的內容:用戶根據id查詢時,所需要的參數值
property屬性指定的內容:將查詢到的信息封裝到account中的User屬性裏
-->
<!-- 只有需要user的時候,纔會根據column指定的uid傳給com.itheima.dao.IUserDao.findById,來查詢user-->
<association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById">
</association>
</resultMap>
<!-- 查詢所有 -->
<select id="findAll" resultMap="accountUserMap">
SELECT * FROM account;
</select>
</mapper>
<!-- com.itheima.dao.IUserDao -->
<mapper namespace="com.itheima.dao.IUserDao">
<!-- 根據id查詢用戶 -->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid}
</select>
</mapper>
【進行測試一】
@Test
public void testFindAll(){
//只是單純地查詢account,並沒有需要user
List<Account> accounts = accountDao.findAll();
}
【輸出結果一】
【進行測試二】
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
//嘗試獲取user,此時執行延遲加載sql語句,查詢user信息
for (Account account : accounts) {
System.out.printf("account ==> %s \n",account);
}
}
【輸出結果二】
【一對多關係延遲加載】
一對一學習之後,一對多就沒什麼難題了。
一、首先還是開啓全局支持懶加載的設置。
二、配置mapper.xml
<!-- com.itheima.dao.IUserDao -->
<mapper namespace="com.itheima.dao.IUserDao">
<!--定義User的resultmap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!--配置user中accounts集合的映射-->
<collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id">
</collection>
</resultMap>
<!-- 查詢所有 -->
<select id="findAll" resultMap="userAccountMap" >
SELECT * FROM USER
</select>
</mapper>
<!-- com.itheima.dao.IAccountDao -->
<mapper namespace="com.itheima.dao.IAccountDao">
<!--根據用戶id查詢賬戶列表-->
<select id="findAccountByUid" resultType="account">
select * from account where UID = #{uid}
</select>
</mapper>