简体   繁体   中英

Hibernate One to One XML mapping not inserting foreign key

I have these classes:

class Parent {
    private int parentId;
    private Child child;
}

class Child {
    private int childId;
    private Parent parent;
}

And the following XML mappings:

<hibernate-mapping>
    <class name="com.package.Parent" table="PARENT">
        <id name="id" type="int" column="parent_col_id"/>
        <one-to-one name="child" class="com.package.Child">
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="com.package.Child" table="Child">
        <id name="id" type="int" column="child_col_id"/>
        <one-to-one name="Parent" class="com.package.Parent">
    </class>
</hibernate-mapping>

MySQL database looks something like this:

ParentDB
parent_col_id    INT(11)      PK NN AI

ChildDB
child_col_id     INT(11)      PK NN AI
name             VARCHAR(45) (none checked)
parent_id        INT(11)     (none checked)

Now let's try to update them!

Session hSession = sessionService.openSession();
Parent parent = hSession.get(Parent.class, parentId);

Child child = new Child();
child.setName = "CooCoo";

parent.setChild(child);
childRepo.insert(child, hSession);
hSession.close();

Now, the problem is that the child is inserted into the DB, but the foreign key is not! Which makes my children be abandoned! Save my children please :( What am I doing wrong?

I tried moving the foreign key column on the parent side.. Still nothing.. How does Hibernate know that the parent_id or child_id column is the foreign id?

It worked after I changed the code into the following:

Changed XML mapping to:

<hibernate-mapping>
    <class name="com.package.Parent" table="PARENT">
        <id name="id" type="int" column="parent_col_id"/>
        <one-to-one name="child" class="com.package.Child" cascade="all"/>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="com.package.Child" table="Child">
        <id name="id" type="int" column="child_col_id">
        <generator class="foreign">
            <param name="property">parent</param>
        </generator>
    </id>
        <one-to-one name="Parent" class="com.package.Parent">
    </class>
</hibernate-mapping>

Changed java code to:

Session hSession = sessionService.openSession();
Parent parent = hSession.get(Parent.class, parentId);

Child child = new Child();
child.setName = "CooCoo";

parent.setChild(child);
child.setParent(parent);
parentRepo.update(parent, hSession);
hSession.close();

In MySQL, the parent_id column was removed, since the foreign ID is set as the primary Key ID.

Hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM