DB:
Code:
create table person
(
personid number not null,
thename varchar2(100) null,
constraint pk_person primary key (personid)
);
create sequence personseq increment by 1 start with 1;
create table address
(
addressid number not null,
personid number not null,
theaddress varchar2(100) null,
constraint pk_address primary key (addressid),
constraint fk_person foreign key (personid) references person(personid)
);
create sequence addressseq increment by 1 start with 1;
Objects:
Person object has
id, name, Address (the whole Address object)
Address object has
id, address, personId (not a Person object, just the id)
Mapping:
Code:
<hibernate-mapping>
<class name="Person" table="PERSON">
<id name="id" column="PERSONID">
<generator class="sequence">
<param name="sequence">PERSONSEQ</param>
</generator>
</id>
<property name="name" column="THENAME"/>
<one-to-one name="address" class="Address" cascade="save-update" constrained="true" property-ref="personId"/>
</class>
<class name="Address" table="ADDRESS">
<id name="id" column="ADDRESSID">
<generator class="sequence">
<param name="sequence">ADDRESSSEQ</param>
</generator>
</id>
<property name="address" column="THEADDRESS"/>
<many-to-one name="personId" class="Person"
cascade="save-update" column="PERSONID" unique="true"/>
</class>
</hibernate-mapping>
So, I want to be able to load my person, and automatically get my Address. The Person doesn't have an Address link it's table, so I want to use the one-to-one and have it load a record from the Address table. But, I get ahead of myself, my question is on the save.
I create a new Person object, and a new Address object.
Code:
Person person = new Person();
Address address = new Address();
address.setAddress("myaddress");
person.setAddress(address);
person.setName("myname");
When I save the Person object, the person gets an id populated (great!), the Address in the Person gets an id (great!), but the personId in the Address, which should be populated with the newly created PersonId, remains null, which fails the insert.
Shouldn't the nested PesonId be populated on a save? Seems sort of useless to have a one-to-one mapping that doesn't actually set the foreign key id when saving. I assume I have something set incorrectly here. Could somebody elighten me?
BTW, I cannot switch it to have an addressId in the person table (obviously simplified examples of my real situation). I need to work with the Person object exclusively. That is, I need to be able to create/save/update Person objects and have the changes to Address objects flow from there.
Thanks in advance,
-- Dave