Reputation: 34424
i am trying to save person along with his address. I have one to one mapping between person and address.Person class is having instance of address. When i created the person table address table also got created. Till here no issues. But when i try to save person , address is not getting saved.Here is my mapping file
<hibernate-mapping>
<class name="com.daasl.Person" table="person">
<id name="id" type="int">
<generator class="increment"/>
</id>
<property name="name" column="cname" type="string"/>
<one-to-one name="address" class="com.daasl.Address"/>
</class>
<class name="com.daasl.Address" table="Address">
<id name="id" type="int">
<generator class="increment"/>
</id>
<property name="personId" type="int"/>
<property name="addressLine1" type="string"/>
</class>
</hibernate-mapping>
i am not sure how create foreign key relationship here (basically i want person id in address table as foreign key to person table) and when i save the data to person table , address should be saved too which is not happening now.Similarily i retrieve data , i should also get the data for address too
Upvotes: 0
Views: 3497
Reputation: 4941
Your one-to-one relationship seems to be ok. If your Address doesn't get saved when you save the associated Person, is probably because you haven't configured cascading.
By default, Hibernate doesn't perform any cascading, therefore only the Person will be saved and not the associated entities. You should do something like:
<one-to-one name="address" class="com.daasl.Address" cascade="save-update"/>
In your Person->Address relationship.
The type of cascading depends on the operation you are performing (save, update, etc) on the Person entity. As per the link above, there are different types of cascading related to such operation - use the one that suits your needs.
Upvotes: 3