Hibernate Association Mappings: Many – To – One

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.

  • Share/Bookmark
Hibernate, Tech Notes

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

(required)

(required)