我们使用Hibernate作为持久层,并具有复杂的对象模型.在不暴露真实数据模型的情况下,我想使用以下简单示例来解释问题.
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
}
Run Code Online (Sandbox Code Playgroud)
使用HBM定义DB映射如下:
<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>
Run Code Online (Sandbox Code Playgroud)
我必须保存Person链接到现有的新填充实例Account.该调用由Web客户端发起,因此在我的层中,我获取引用其实例的Person实例Account仅保存其ID.
如果我尝试调用saveOrUpdate(person)以下异常抛出:
org.hibernate.TransientObjectException:
object references an unsaved transient instance - save the transient instance before flushing:
com.mycompany.model.Account
Run Code Online (Sandbox Code Playgroud)
为了避免这种情况,我必须找到AccountID 的持久对象然后调用person.setAccount(persistedAccount).在这种情况下一切正常.
但在现实生活中,我处理了几十个相互引用的实体.我不想为每个引用编写特殊代码.
我想知道这个问题是否存在某种通用解决方案.
要保留一个实体,您只需要引用其直接依赖项.这些其他实体引用其他实体的事实并不重要.
最好的方法是使用代理来获取引用实体的代理,甚至不需要访问数据库session.load(Account.class, accountId).
您正在做的是正确的事情:获取对持久帐户的引用,并将此引用设置为新创建的帐户.