JPA @OneToMany及懶加載無(wú)效
@OneToOne @ManyToMany使用不做過(guò)多解釋,重點(diǎn)解決“懶加載無(wú)效問(wèn)題”。
示例:
@OneToMany
teacher 和 student是一對(duì)多關(guān)系
只需要在studentList上使用@OneToMany注解,對(duì)應(yīng)的參數(shù)為 懶加載、級(jí)聯(lián)操作、子表外鍵
我為了驗(yàn)證懶加載是否生效,在debug模式下發(fā)現(xiàn)懶加載并沒(méi)有生效。在正常模式下,返回到頁(yè)面也是有studentList的數(shù)據(jù)。于是開(kāi)始排坑,逐漸懷疑人生。。
直到看到了某國(guó)際友人說(shuō)的這么一句話。
It seems to be a debugging artifact.
At debugging time, because the transaction is still open, the watched lazy loaded entity properties will be loaded at the breakpoint evaluation time.
于是在application.properties中加上spring.jpa.show-sql=true,打開(kāi)執(zhí)行的SQL。
debug下,執(zhí)行到29行,共執(zhí)行了以下兩句SQL:
Hibernate: select teacher0_.id as id1_1_0_, teacher0_.age as age2_1_0_, teacher0_.name as name3_1_0_ from teacher teacher0_ where teacher0_.id=? Hibernate: select studentlis0_.teacher_id as teacher_4_0_0_, studentlis0_.id as id1_0_0_, studentlis0_.id as id1_0_1_, studentlis0_.addr as addr2_0_1_, studentlis0_.name as name3_0_1_, studentlis0_.teacher_id as teacher_4_0_1_ from student studentlis0_ where studentlis0_.teacher_id=?
開(kāi)始只查詢了teacher表,緊接著進(jìn)行了關(guān)聯(lián)查詢,結(jié)合上面那句話猜測(cè)可能是debug導(dǎo)致的。而在正常模式下啟動(dòng),也是兩條SQL,猜測(cè)可能是返回前端時(shí),序列化自動(dòng)調(diào)用了getStudentList()方法,導(dǎo)致執(zhí)行了第二條SQL。
于是新建TeacherDto.class
并在controller中return teacherDto,不直接返回teacher。
在正常模式下啟動(dòng),果然只有一條SQL,沒(méi)有進(jìn)行級(jí)聯(lián)查詢。
Hibernate: select teacher0_.id as id1_1_0_, teacher0_.age as age2_1_0_, teacher0_.name as name3_1_0_ from teacher teacher0_ where teacher0_.id=?
至此踩坑結(jié)束……
小結(jié)一下吧
在使用@OneToOne、@OneToMany、@ManyToMany時(shí),只需要加上參數(shù)fetch = FetchType.LAZY即可。
在debug模式下,會(huì)自動(dòng)進(jìn)行級(jí)聯(lián)查詢,導(dǎo)致懶加載無(wú)效,可能是idea方便開(kāi)發(fā)人員調(diào)試,故意這樣設(shè)置的。
在接口返回時(shí),避免直接返回entity,可返回Dto或Vo。
實(shí)現(xiàn)JPA的懶加載和無(wú)外鍵
在網(wǎng)上找了很多jpa的懶加載,要不就是抓取策略,要不就隨便加個(gè)fetch=FetchType.LAZY
其實(shí)jpa實(shí)現(xiàn)懶加載非常簡(jiǎn)單,其實(shí)和mybatis是一樣的,就是不要調(diào)用對(duì)應(yīng)屬性的get方法就可以了
例如
很多接口輸出對(duì)象時(shí)都會(huì)用 BeanUtils.copyProperties()將實(shí)體轉(zhuǎn)為dto輸出,這時(shí)候使用它的重載方法copyProperties(Object source, Object target, String… ignoreProperties)就可以實(shí)現(xiàn)懶加載了
代碼如下
public class NoticeRecord { @OneToMany(fetch=FetchType.LAZY) @JoinColumn(name = "noticeId",foreignKey = @ForeignKey(name = "null")) private List<NoticeSendeeRecord> noticeSendeeRecords; }
轉(zhuǎn)換時(shí)使用
這個(gè)重載方法的作用就是轉(zhuǎn)換是忽略noticeRecord中noticeSendeeRecords屬性
BeanUtils.copyProperties(noticeRecord,noticeRecordDTO,"noticeSendeeRecords");
這樣就實(shí)現(xiàn)jpa的懶加載了,檢查輸出sql語(yǔ)句,也只有查詢NoticeRecord 的語(yǔ)句,沒(méi)有查詢NoticeSendeeRecord的語(yǔ)句
而不讓jpa產(chǎn)生外鍵使用 foreignKey = @ForeignKey(name = “null”) 就可以了
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/R_o_b_o_t_/article/details/115400514