通过使用hibernate引用依赖实体来保存实体 [英] saving entity with referenced dependent entities using hibernate

查看:133
本文介绍了通过使用hibernate引用依赖实体来保存实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用Hibernate作为持久层,并且有复杂的对象模型。没有公开真实的数据模型,我想用下面的简单例子来解释这个问题。

We are using Hibernate as persistency layer and have complex object model. Without exposing the real data model I want to explain the problem using the following simple example.

class Person {
    private Integer id; //PK
    private String name;
    private Account account;
    // other data, setters, getters
}


class Account {
    private Integer id; //PK
    // other data, setters, getters
}

数据库映射使用HBM定义如下:

The DB mapping is defined using HBM as following:

 <class name="Person" table="PERSON">
    <id name="id" column="ID">
        <generator class="native"/>
    </id>
    <version name="version" type="java.lang.Long"/>
    <property name="name" type="java.lang.String" length="50" column="NAME"/>
    <many-to-one name="account" column="ACCOUNT_ID"
                class="com.mycompany.model.Account"/>

</class>

我必须保存 Person的新填充实例链接到现有帐户。这个调用是由web客户端发起的,所以在我的层中,我得到了Person引用的实例,该实例引用了 Account 的实例,该实例仅保存其ID。

I have to save new populated instance of Person linked to existing Account. The call is originated by web client, so at my layer I get instance of Person referenced to instance of Account that holds its ID only.

如果我尝试调用 saveOrUpdate(person),则会引发以下异常:

If I try to call saveOrUpdate(person) the following exception is thrown:

org.hibernate.TransientObjectException: 
object references an unsaved transient instance - save the transient instance before flushing: 
com.mycompany.model.Account

为了避免这种情况,我必须找到 Account ,然后调用 person.setAccount(persistedAccount)。在这种情况下,一切正常。

To avoid this I have to find the persisted object of Account by ID and then call person.setAccount(persistedAccount). In this case everything works fine.

但在现实生活中,我处理数十个相互引用的实体。我不想为每个引用编写特殊代码。

But in real life I deal with dozens of entities referenced to each other. I do not want to write special code for each reference.

我想知道是否有针对此问题的某种通用解决方案。

I wonder whether there is some kind of generic solution for this problem.

推荐答案

要坚持一个实体,只需要引用其直接依赖关系。这些其他实体引用其他实体并不重要。

To persist one entity, you just need to have the references to its direct dependencies. The fact that these other entities reference other entities doesn't matter.

最好的方法是使用 session.load(Account。)来获取被引用实体的代理,甚至不用访问数据库。 class,accountId)

您正在做的是正确的事情:获取对持久帐户的引用,并设置此参考新创建的帐户。

What you're doing is the right thing to do: get a reference to the persistent account, and set this reference into the newly created account.

这篇关于通过使用hibernate引用依赖实体来保存实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆