Hibernate is loading lazy objects without being asked for

[亡魂溺海] 提交于 2019-12-11 04:41:46

问题


In order to keep transfered data small I created two entities for my files in the database. The fileheader to keep some general informations about the files and the fileblob, including fileId and the blob. Often, I only need to ask for general fileinformations. If I now ask for a list of fileheaders, hibernate unfortunatelly selects the fileblob too (each one in a single select). So here is my example:

Extract from Fileh.class:

  @OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY)
  @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
  private Fileblob fileblob;

Extract from selection:

  Criteria createCriteria = persistentSession.createCriteria(Fileh.class);

  List list = createCriteria.list();

ConsoleLog:

Hibernate: 
    select
        this_.`ID` as ID1_78_0_,
        this_.`CHDATE` as CHDATE2_78_0_,
        this_.`CHUSER` as CHUSER9_78_0_,
        this_.`CRDATE` as CRDATE3_78_0_,
        this_.`CRUSER` as CRUSER10_78_0_,
        this_.`EXTENSION` as EXTENSIO4_78_0_,
        this_.`NAME` as NAME5_78_0_,
        this_.`SIZE` as SIZE6_78_0_,
        this_.`VALID_FROM` as VALID_FR7_78_0_,
        this_.`VALID_TO` as VALID_TO8_78_0_ 
    from
        CORE.`FILEH` this_
Hibernate: 
    select
        fileblob0_.`ID` as ID1_77_0_,
        fileblob0_.`FILEBLOB` as FILEBLOB2_77_0_ 
    from
        CORE.`FILEBLOB` fileblob0_ 
    where
        fileblob0_.`ID`=?
Hibernate: 
    select
        fileblob0_.`ID` as ID1_77_0_,
        fileblob0_.`FILEBLOB` as FILEBLOB2_77_0_ 
    from
        CORE.`FILEBLOB` fileblob0_ 
    where
        fileblob0_.`ID`=? .....(and so on)

Am I wrong with my assumption, that fetch = FetchType.LAZY should be sufficient for my purpose?

Thanks in advance for your hints and suggestions. I just think I´m barking up the wrong tree...

Kind regards, Vincent

Edit: Started to dive into hibernate sourcecode. In DefaultLoadEventListener.proxyOrLoad(...) hibernate decides weather to load as proxy or not. In my example following option is passed: LoadEventListener.INTERNAL_LOAD_NULLABLE which results in accessing the database. Just don´t understand why yet....

Edit2: Problem solved: added optional = false to OneToOne-annotation:

@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
  @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
  private Fileblob fileblob;

回答1:


Problem solved, adding optional = false in the OneToOne-annotation does the trick.

See similarity post



来源:https://stackoverflow.com/questions/43678271/hibernate-is-loading-lazy-objects-without-being-asked-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!