views:

320

answers:

4

Assume that I have Person and Address Classes and they have different tables in DB.

One Person can have one Address Class in it. This is the important part for me. One Person can have only one Address as it s child element and i want to keep them in different tables in DB.

Normally i know that i need to hold them in the same table, but my scenario needs this.

(and also it looks like a one-to-many but i dont want to have a collection just for one object)

Person     Address
-------    -------
id         id
Name       PersonId
           StreetName

And class code

Person                                                 
--------
public virtual long Id{get;set;}
public virtual Address MyAddress {get;set;}

As you see i want to get Address Property in Person when i get any Person ? But they are in different tables. How can this mapping be done ?

Thanks in advance

A: 

Are you sure it's a one to one relationship? I would assume it's a many-to-one relationship as usually more then one person can live at a certain address.

Anyways if it's a many-to-one relationship I'd map them like so. What I would do in your case is remove the PersonId FK from the Address table and put reference the Address Table from the Person table so you'd have something like this.

Person    Address
------    -------
id        id
Name      StreetName
AddressId

<many-to-one name="MyAddress" class="Address" column="AddressId"/>

and if you do insist on a one-to-one relationship I would recommend merging the two tables together.

CalvinR
Thanks but in my scenario the owner of the relation must be Address not the Person. I mean Address need to hold PersonId
Barbaros Alp
A: 

I have used the code below in Person mapping to get it done.

<one-to-one lazy="proxy" name="MyAddress" class="Address" property-ref="PersonId" cascade="delete" />

Hope helps someone else

Barbaros Alp
+2  A: 

You can't map Address using a component because it has its own table. You could use it if you had all fields in just one table. From the Hibernate reference:

The component element maps properties of a child object to columns of the table of a parent class.

You should use a one-to-one relationship to map the tables and classes in you scenario.

cprats
Thanks for your answer, i get it.I have used one-to-one for this situation.Thanks again
Barbaros Alp
+1  A: 

To enforce the one-to-one in the database, you can also put a unique constraint on the PersonId in the Address table.

Andy White