什么是延遲加載?
延遲加載也叫懶加載、惰性加載,使?延遲加載可以提?程序的運行效率,針對于數據持久層的操作, 在某些特定的情況下去訪問特定的數據庫,在其他情況下可以不訪問某些表,從?定程度上減少了 Java 應?與數據庫的交互次數。
查詢學?和班級的時,學生和班級是兩張不同的表,如果當前需求只需要獲取學shengsheng的信息,那么查詢學 ?單表即可,如果需要通過學?獲取對應的班級信息,則必須查詢兩張表。 不同的業務需求,需要查詢不同的表,根據具體的業務需求來動態減少數據表查詢的?作就是延遲加載。
如何使用延遲加載?
1.在 config.xml 中開啟延遲加載
1
2
3
4
5
6
|
< settings > <!-- 打印SQL--> < setting name = "logImpl" value = "STDOUT_LOGGING" /> <!-- 開啟延遲加載 --> < setting name = "lazyLoadingEnabled" value = "true" /> </ settings > |
2.將多表關聯查詢拆分成多個單表查詢
StudentRepository中
1
|
public Student findByIdLazy( long id); |
StudentRepository.xml
1
2
3
4
5
6
7
8
9
10
|
< 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
1
|
public Classes findByIdLazy(long id); |
1
2
3
4
5
6
7
8
|
< 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延遲加載的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/DrLai/article/details/119753979