saving entity with referenced dependent entities using hibernate

2022-09-04 03:13:25

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. PersonAccountAccount

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. Accountperson.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.


答案 1

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.

The best way to do it is to get a proxy to the referenced entity, without even hitting the database, using .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.


答案 2

Hibernate allows you to use just reference classes with ID, you don't need to do session.load().

The only important thing is that if your reference object has VERSION, than the version must be set. In your case you have to specify version of Account object.


推荐