Java 計算某個數的階乘
阿新 • • 發佈:2021-01-12
一、什麼叫延遲載入、立即載入
1.什麼是延遲載入
在真正需要使用資料時才發起查詢,不用的時候不進行查詢。按需載入(懶載入)
2. 什麼是立即載入
不管用不用,只要一呼叫方法,馬上發起查詢。
二、Mybatis中的延遲載入
需求:
在一對多中,當我們有一個使用者,它有10個角色。
在查詢使用者時,使用者下的角色資訊應該是,什麼時候使用,什麼時候查詢的。
在查詢角色時,賬戶的所屬使用者資訊應該是隨著賬戶查詢時一起查詢出來。
在對應的四種表關係中:
一對多,多對一,一對一,多對多
一 對多,多對多:通常情況下我們都是採用延遲載入。
多對一,一對一:通常情況下我們都是採用立即載入。
例:以使用者和賬戶關係為例,查詢一個賬戶時顯示當前賬戶的所屬使用者
查詢方法
1.dao層介面
public interface IAccountDao {
/**
* 查詢所有賬戶,同時還要獲取到當前賬戶的所屬使用者資訊
* @return
*/
List<Account> findAll();
}
2.對映檔案:
<resultMap id="accountUserMap" type="account"> <id property="id" column="id"></id> <result property="uid" column="uid"></result> <result property="money" column="money"></result> <!-- 一對一的關係對映:配置封裝user的內容 select屬性制定的內容:查詢使用者的唯一標識 column屬性指定的內容:使用者根據id時,所需要的引數值的值--> <association property="user" column="uid" javaType="user" select="com.rpf.dao.IUserDao.findById"></association> </resultMap> <!-- 查詢所有 --> <select id="findAll" resultMap="accountUserMap"> select * from account </select>
3.Mybatis主配置檔案配置開啟懶載入
<!--加入settings--> <settings> <!--開啟Mybatis支援延遲載入--> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"></setting> </settings>
4.測試
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
}
效果圖
沒開啟延遲載入之前執行了三條
開啟了延遲載入後 執行了一條語句
一對多實現延遲載入:
1. dao層介面
List findAll();
2.對映檔案
//user
<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.rpf.dao.AccountDao.findAccountByUid" column="id"></collection>
</resultMap>
<!-- 查詢所有 -->
<select id="findAll" resultMap="userAccountMap">
select * from user
</select>
<!-- 根據id查詢使用者 -->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid}
</select>
<!-- 根據使用者id查詢賬戶列表 account -->
<select id="findAccountByUid" resultType="account">
select * from account where uid=#{uid}
</select>
3.測試類:
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
}
只查詢了使用者並沒有查使用者下賬戶的資訊