Hibernate Unidirectional One to One Association Mapping - Hibernate
Home » Hibernate, Tech Notes

Hibernate Unidirectional One to One Association Mapping

10 March 2009 No Comment

Hibernate one-to-one mapping, this is a simple business. One entity linked to one and only one other entity. Not in the practical world scenario, but if we continue our previous example, then one customer having only one address. This is how the rule will be defined at the three places of our concern.

Database:
Customer needs to be linked with one and only one address and vice versa. Customer table will have the address id column with unique constraint. Our table creating scripts will be like –

TAB_CUSTOMER
 CUSTOMER_ID - Number - Not NULL Primary Key
 ADDRESS_ID - Number - Not NULL, unique Foreign Key From tab_address table

TAB_ADDRESS
 ADDRESS_ID - Number - Not NULL Primary Key

Simple, isn’t it? Let us take this to one level above, i.e. hibernate mapping layer.

Hibernate Mapping:
Just check the many-to-one mapping used with unique constraint on reference column.


 
 


 
  
 

We cannot do much to implement one to one relationship. See below.

Java:
Only constraint that we can ensure is – the customer is linked to one address but not uniquely.

public class Customer {
private Long id;
private Address address;
// getter/setter for id & address fields
}
public class Address {
  private Long id;
  //getter/setter for id
}

There is one more way to implement this relation, which is using one – to – one mapping on primary keys of two tables.

Database:
Scripts may look weird but this will work -

TAB_CUSTOMER
 CUSTOMER_ID - Number - Not NULL Primary Key

TAB_ADDRESS
 CUSTOMER_ID - Number - Not NULL Primary Key Foreign key from tab_customer

Hope you have noticed the primary key of address table is also customer id.

Hibernate Mapping:


  
    
  


  
    
address
    
  
  

Java:
Feel lucky, you have nothing to change as compared to the previous (many-to-one) approach.

 

More Related Posts in Hibernate, Tech Notes

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.