Hibernate - 加载孩子

时间:2015-03-31 07:40:17

标签: java hibernate nhibernate-mapping

我有以下Hibernate Mappings:

<class name="Database.Content" table="..." schema="" catalog="...">
    <id name="id">
        <column name="id" sql-type="int" not-null="true"/>
    </id>
    <property name="week">
        <column name="week" sql-type="int"/>
    </property>
    <property name="day">
        <column name="day" sql-type="int"/>
    </property>
    <property name="hour">
        <column name="hour" sql-type="int"/>
    </property>
    <property name="type">
        <column name="type" sql-type="int" not-null="true"/>
    </property>
    <many-to-one name="group" class="Database.Group">
        <column name="group"/>
    </many-to-one>
    <many-to-one name="table" class="Database.Table">
        <column name="table" not-null="true"/>
    </many-to-one>
    <list name="entries" inverse="true" table="...">
        <key>
            <column name="content" not-null="true"/>
        </key>
        <list-index column="id"/>
        <one-to-many not-found="ignore" class="Database.Entry"/>
    </list>
</class>
<class name="Database.Entry" table="..." schema="" catalog="...">
    <id name="id">
        <column name="id" sql-type="int" not-null="true"/>
    </id>
    <property name="teacher">
        <column name="teacher" sql-type="int" not-null="true"/>
    </property>
    <property name="course">
        <column name="course" sql-type="int" not-null="true"/>
    </property>
    <property name="room">
        <column name="room" sql-type="int" not-null="true"/>
    </property>
    <property name="p">
        <column name="p" sql-type="int" not-null="true"/>
    </property>
    <many-to-one name="content" class="Database.Content" fetch="join" lazy="false">
        <column name="content" not-null="true"/>
    </many-to-one>
</class>

现在,我尝试使用相应的contents

查询所有entries
List<Content> contents = session.createQuery("from Content c WHERE c.day IN :days ").setParameterList("days", days).list();

查询返回正确的响应。但是,当我执行以下操作时:

contents.get(0).getEntries()

有一堆空值。为每个entries急切加载所有相应content的正确方法是什么?

我有大约20,000条content条记录,而且大多数记录只有一条记录。

如果我为lazy="false"列表设置了entries,则会出现Java heap space错误。


我最终获取entries并加入contents

List<Entry> entries = session.createQuery("select e from Entry e Join e.content c WHERE c.day IN :days ").setParameterList("days", days).list();

我还将lazy更改为proxy

<many-to-one name="content" class="Database.Content" fetch="join" lazy="proxy">
    <column name="content" not-null="true"/>
</many-to-one>

2 个答案:

答案 0 :(得分:1)

添加lazy = false属性:

 <list name="entries" inverse="true" table="up_timetable_entries" lazy="false">

希望帮助你!

答案 1 :(得分:1)

尝试致电:

contents.get(0).getEntries()大小();

强制hibernate加载孩子。