最近項(xiàng)目中遇到了個(gè)hibernate lazy延遲加載的問題,實(shí)體關(guān)系如下A,B
public class A {
@OneToOne(fetch=FetchType.LAZY,mappedBy = "a")
B b;
}
public class B {
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "A_ID_FK")
A a;
}
情況是:取A的對(duì)象時(shí),就算設(shè)置了lazy,結(jié)果還是eager馬上獲取的, hibernate打印出的也是多了一條SQL語(yǔ)句;
但當(dāng)取B的對(duì)象時(shí),設(shè)置了的lazy就生效了,只有一條SQL語(yǔ)句
查了不少資料,在robin的文章中找到這樣的話:"先來(lái)說(shuō)說(shuō)Hibernate吧。Hibernate確實(shí)功能強(qiáng)悍,但是Hibernate不夠易用,而且有一些明顯的缺陷:one-to-one必須通過bytecode enhancement才能lazy loading",這里說(shuō)出OneToOne存在這樣的缺陷,然而所說(shuō)的bytecode enhancement不是很清楚什么意思,猜測(cè)是用cglib進(jìn)行一些對(duì)象的動(dòng)態(tài)改變.
在論壇中找到這樣的一段解釋:
Does lazy loading of one-to-one associations work? Lazy loading for
one-to-one associations is sometimes confusing for new Hibernate users.
If you consider one-to-one associations based on shared primary keys
(chapter 7, section 7.1.1, “Shared primary key associations”), an association
can be proxied only if it’s constrained="true". For example, an
Address always has a reference to a User. If this association is nullable
and optional, Hibernate first would have to hit the database to find out
whether a proxy or a null should be applied—the purpose of lazy loading
is to not hit the database at all. You can enable lazy loading through
bytecode instrumentation and interception, which we’ll discuss later.
綜上的原因得出兩種解決方法:
1.將OneToOne改為OneToMany,但幾點(diǎn)是改變了實(shí)體關(guān)系,對(duì)已有代碼也有存在影響
2.將OneToOne的主控方設(shè)在你需要lazy loading的實(shí)體那里,但兩個(gè)都需要lazy loading呢
You can enable lazy loading through
bytecode instrumentation and interception, which we’ll discuss later. 對(duì)這句話還要繼續(xù)尋找答案
只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。 | ||
![]() |
||
網(wǎng)站導(dǎo)航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||