itVincent Blog - Java Working Fun!

技术引领时代!
posts - 117, comments - 181, trackbacks - 0, articles - 12

OneToOne lazy loading不生效的问题

Posted on 2008-11-04 13:38 itVincent 阅读(2046) 评论(0)  编辑  收藏

最近项目中遇到了个hibernate lazy延迟加载的问题,实体关系如下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的对象时,就算设置了lazy,结果还是eager马上获取的, hibernate打印出的也是多了一条SQL语句;
但当取B的对象时,设置了的lazy就生效了,只有一条SQL语句

查了不少资料,在robin的文章中找到这样的话:"先来说说Hibernate吧。Hibernate确实功能强悍,但是Hibernate不够易用,而且有一些明显的缺陷:one-to-one必须通过bytecode enhancement才能lazy loading",这里说出OneToOne存在这样的缺陷,然而所说的bytecode enhancement不是很清楚什么意思,猜测是用cglib进行一些对象的动态改变.

在论坛中找到这样的一段解释:
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,但几点是改变了实体关系,对已有代码也有存在影响
2.将OneToOne的主控方设在你需要lazy loading的实体那里,但两个都需要lazy loading呢

You can enable lazy loading through
bytecode instrumentation and interception, which we’ll discuss later.
对这句话还要继续寻找答案


只有注册用户登录后才能发表评论。


网站导航: