sergionni
sergionni

Reputation: 13510

Hibernate:one-to-one related entity inserted into DB instead of to be updated

@ManagedBean
@SessionScoped
public class User {
private Person person;
...

user.hbm.xml

<hibernate-mapping>
    <class name="entry.User" table="users">
        <id name="usaa">
            <generator class="increment"/>
        </id>
        <property name="username" column="username"/>
        <property name="password" column="password"/>
        <property name="enabled" column="enabled"/>

        <many-to-one name="person" class="entry.Person" column="perid" not-null="true" cascade="all" unique="true"/>            
    </class>
</hibernate-mapping>

person.hbm.xml

<hibernate-mapping>
    <class name="entry.Person" table="person">
        <id name="id" column="perid">
            <generator class="increment"/>
        </id>
        <property name="firstName" column="firstname"/>
        <property name="lastName" column="lastname"/>
        <property name="middleName" column="middlename"/>
        <property name="dob" column="dob"/>
    </class>
</hibernate-mapping>

Thus, one-to-one relation designed above.

Correctly working DAO method:

public void createUser(User user) {
user.setPerson(new Person());
getHibernateTemplate().save(user);
..

when User is inserted into DB,that Person is inserted into DB automatically also.It's OK.

Unexpectedly working DAO method:

public void editUser(User user, Person person) {
user.setPerson(person);
getHibernateTemplate().update(user);
...

Problem occurred, when User is updated with new Person data.

New Person id generated and one new row inserted into Person table.

How to do that,Person appropriate row to be updated and not inserted?

Thank you for help.

Assumption:

I assume,that problem is in autoincrementing ids when refer to the entity.
It looks like, autoincrementing should be avoided in case of update or saveOrUpdate method calls.
Autoincrementing should be called,when entity firstly created and inserted into DB.

Upvotes: 1

Views: 1640

Answers (1)

ManuPK
ManuPK

Reputation: 11829

Your assumptions are correct,

It looks like, autoincrementing should be avoided in case of update or saveOrUpdate method calls. Autoincrementing should be called,when entity firstly created and inserted into DB.

You do not have to wroory about all these, hibernate will use a simple rule to do this, when the id of the object is null it fires an insert query if it is any other value it fires an update query with that value.

In your case before you save user, set the person id to oldPersonId.

public void editUser(User user, Person person) {
person.SetId(oldPersonId);
user.setPerson(person);
getHibernateTemplate().update(user);

This will fire the update query instead of insert.

Upvotes: 2

Related Questions