saving entity with referenced dependent entities using 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
}
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>
I have to save new populated instance of linked to existing . The call is originated by web client, so at my layer I get instance of Person referenced to instance of that holds its ID only. Person
Account
Account
If I try to call the following exception is thrown:saveOrUpdate(person)
org.hibernate.TransientObjectException:
object references an unsaved transient instance - save the transient instance before flushing:
com.mycompany.model.Account
To avoid this I have to find the persisted object of by ID and then call . In this case everything works fine. Account
person.setAccount(persistedAccount)
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.