I have two objects that have a one-to-one relation. When I'm adding them to the DB I first create a separate instance of the two objects. The I assign the child object to the parent. The problem is that when inserted into the db (MySQL) the child does not get the parents id.
Simplified example of my code:
Code:
User user = new User(username,password);
Person person = new Person(name, address);
u.setPerson(person);
session.save(user);
session.flush();
I then get the exception
General error, message from server: "Column 'userID' cannot be null". The userID field has the not null constraint, so I understand the message.
My question is: how can I assign the right userID to the person. My workaround is to set some static userID on the person object and then after the user is saved, retrieve the right userID and update the person.
There must be a better way to do this?
Mapping file for user (parent)
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping >
<class name="package.User" table="user" >
<id name="userID" column="userID">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="username" column="username" type="java.lang.String" />
<property name="password" column="password" type="java.lang.String" />
<one-to-one name="person" class="package.Person" property-ref="brukerID" />
</class>
</hibernate-mapping>
Mapping file for Person (child)
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping >
<class name="package.Person" table="person" >
<id name="personID" column="personID" type="int" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="userID" column="userID" type="int" />
<property name="name" column="name" type="java.lang.String" />
<property name="address" column="adress" type="java.lang.String" />
</class>
</hibernate-mapping>