Hibernate正在加载惰性对象而不会被要求

时间:2017-04-28 10:42:50

标签: hibernate lazy-loading

为了保持传输的数据很小,我在数据库中为我的文件创建了两个实体。 fileheader保存一些关于文件和fileblob的一般信息,包括fileId和blob。 通常,我只需要询问一般的文件信息。如果我现在要求一个文件头的列表,hibernate也不幸地选择了fileblob(每个选择一个)。所以这是我的例子:

从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;

从选择中提取:

  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)

我的假设是错误的, fetch = FetchType.LAZY 应该足以达到我的目的吗?

提前感谢您的提示和建议。我只是觉得我在错误的树上咆哮......

亲切的问候, 文森特

编辑:开始深入了解hibernate源代码。在DefaultLoadEventListener.proxyOrLoad(...)中,hibernate决定将天气作为代理加载。在我的示例中,传递了以下选项:LoadEventListener.INTERNAL_LOAD_NULLABLE,这导致访问数据库。只是不明白为什么......

编辑2:问题已解决:将optional = false添加到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 个答案:

答案 0 :(得分:0)

问题解决了,在OneToOne-annotation中添加optional = false就可以了。

参见相似性post