java工程師進階之MyBatis延遲加載的使用
什么是延遲加載?
延遲加載也叫懶加載、惰性加載,使⽤延遲加載可以提⾼程序的運行效率,針對于數(shù)據(jù)持久層的操作, 在某些特定的情況下去訪問特定的數(shù)據(jù)庫,在其他情況下可以不訪問某些表,從⼀定程度上減少了 Java 應⽤與數(shù)據(jù)庫的交互次數(shù)。
查詢學⽣和班級的時,學生和班級是兩張不同的表,如果當前需求只需要獲取學shengsheng的信息,那么查詢學 ⽣單表即可,如果需要通過學⽣獲取對應的班級信息,則必須查詢兩張表。 不同的業(yè)務需求,需要查詢不同的表,根據(jù)具體的業(yè)務需求來動態(tài)減少數(shù)據(jù)表查詢的⼯作就是延遲加載。
如何使用延遲加載?
1.在 config.xml 中開啟延遲加載
<settings> <!-- 打印SQL--> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 開啟延遲加載 --> <setting name="lazyLoadingEnabled" value="true"/> </settings>
2.將多表關聯(lián)查詢拆分成多個單表查詢
StudentRepository中
public Student findByIdLazy(long id);
StudentRepository.xml
<resultMap id="studentMapLazy" type="entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="entity.Classes" select="repository.ClassesRepository.findByIdLazy" column="cld">
</association>
</resultMap>
<select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
-- select s.id ,s.name,c.id as cid,c.name as cname from student s,classes c where s.id =1 and s.cld=c.id;
select * from student where id=#{id};
</select>
ClassesRepository
public Classes findByIdLazy(long id);
<resultMap id="classesMap" type="entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
<collection property="students" ofType="entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
</collection>
</resultMap>
以上就是java工程師進階之MyBatis延遲加載的使用的詳細內容,更多關于java之MyBatis延遲加載的資料請關注腳本之家其它相關文章!
相關文章
Spring Boot LocalDateTime格式化處理的示例詳解
這篇文章主要介紹了Spring Boot LocalDateTime格式化處理的示例詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
java判斷兩個List<String>集合是否存在交集三種方法
這篇文章主要介紹了三種判斷Java中兩個List集合是否存在交集的方法,分別是使用retainAll方法、使用Stream和anyMatch以及使用Set提高性能,每種方法都有其適用場景和優(yōu)缺點,需要的朋友可以參考下2025-03-03
SpringBoot使用Maven打包異常-引入外部jar的問題及解決方案
這篇文章主要介紹了SpringBoot使用Maven打包異常-引入外部jar,需要的朋友可以參考下2020-06-06

