Hibernate Unidirectional Association Mappings: Many - To - One - Hibernate
Home » Hibernate, Tech Notes

Hibernate Association Mappings: Many – To – One

2 March 2009 No Comment

Many – to -one is a unidirectional relation i.e. it establishes relation amongst many entities with one entity. It will be clear with this example. Suppose there are 5 people staying in a house. Each of them wants to buy a mobile phone and they give same address to the service provider. Now the service provider’s database will have same address linked to these 5 people. This is exactly the scenario where many entities (customers) are linked to one entity (address).

In database this is handled by providing foreign key reference of address (primary key) in customer table. But this column in customer table will not contain unique values of customer.
Thus Many customers – are linked to – one address.

Let us put our example in code.
This is how our table’s primary columns look:

TAB_CUSTOMER
	CUSTOMER_ID Number Not NULL Primary Key
	ADDRESS_ID Number Not NULL Foreign Key From Address table

TAB_ADDRESS
	ADDRESS_ID - Number Not NULL Primary Key

Many – to – one mapping of above scenario will look like this.


   
  
  



   
  

Now the Java code should also map to our this mapping definition.

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 field
}

Point(s) to Remember:
Foreign Key reference column does not contain unique key constraint.

 

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.