Hibernate一对多+延迟加载

时间:2011-02-13 15:08:50

标签: java hibernate hibernate-mapping

我有一个Account实体和一个AccountTransaction实体。

帐户1< ----> n AccountTransaction

在我的AccountTransaction.hbm.xml中,我指定了多对一关系:

<hibernate-mapping>
<class name="com.walshk.accountmanager.domain.AccountTransaction" table="AccountTransaction">

    <id name="id" type="long" column="transaction_id">
        <generator class="increment"/>
    </id>

    <property name="date" not-null="true" type="date" column="transaction_date"/>

    <property name="description" not-null="true" column="transaction_description" length="500"/>

    <property name="amount" column="transaction_amount" not-null="true"/>

    <many-to-one name="account" column="account_id" not-null="true" cascade="all" lazy="false"/>

</class>
</hibernate-mapping>

这允许我使用

按帐户查找AccountTransactions
Criteria criteria = session.createCriteria(AccountTransaction.class)
    .add(Restrictions.eq("account", account));

还允许我使用AccountTransaction#getAccount();

获取Account实例

我现在要做的是提供一种获取帐户的方法,例如

Criteria criteria = session.createCriteria(Account.class).add(Restrictions.eq("id", id));

但我也希望Account实体有一个方法

List<AccountTransaction> getTransactions();

我希望这可以延迟加载,因为我甚至可能不需要列出事务。

由于我已经从AccountTransaction指定多对一关系,我现在如何指定一对多关系,让我从另一个方向进行访问。

此外,处理延迟加载的最佳方法是什么,我是否必须为每个实体分配会话而不关闭会话?我可能会打开太多的会话。

感谢。

2 个答案:

答案 0 :(得分:2)

如果您在Account类hibernate映射中添加一对多关联,您将获得:

List<AccountTransaction> getTransactions();
来自任何ORM创建工具的

。 这种关联的一个参数是加载类型 - 我不熟悉XML映射中的确切语法,因为我们使用注释,但您可以在hibernate XML映射的任何参考/文档页面中找到它。

答案 1 :(得分:1)

为了使用延迟加载,您应该在视图中启用Open Session。 如果您正在使用Spring集成,那么您有OpenSesionInViewIntereptor / OpenSessionInViewFilter

如果您在没有Spring集成的情况下使用本机Hibernate,那么您可以自己实现它。 请阅读以下内容:

http://community.jboss.org/wiki/OpenSessioninView

希望它有所帮助。