itVincent Blog - Java Working Fun!

          技術引領時代!
          posts - 117, comments - 181, trackbacks - 0, articles - 12

          OneToOne lazy loading不生效的問題

          Posted on 2008-11-04 13:38 itVincent 閱讀(2056) 評論(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.
          對這句話還要繼續尋找答案


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 安达市| 钟祥市| 富蕴县| 宁强县| 上思县| 明星| 石家庄市| 麻城市| 章丘市| 奉节县| 建瓯市| 耒阳市| 五大连池市| 镇安县| 眉山市| 吉安市| 鄂温| 漳平市| 富平县| 晋江市| 宕昌县| 濮阳县| 青海省| 泗阳县| 潮州市| 西乡县| 皮山县| 昆山市| 旌德县| 沂水县| 新兴县| 社旗县| 德州市| 天门市| 通许县| 林甸县| 蛟河市| 晋州市| 扎囊县| 高密市| 锡林郭勒盟|