One to One Mapping in Hibernate

One to one mapping in Hibernate, 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.

One to One Mapping in Hibernate:

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

<class name=”Customer” table=” TAB_CUSTOMER”>
<id name=”id” column=”CUSTOMER_ID”><generator class=”native”/></id>
<many-to-one name=” Address ” column=” ADDRESS_ID ” not-null=”true” unique=”true”/>
</class>
<class name=”Address” table=” TAB_ADDRESS”>
<id name=”id” column=” ADDRESS_ID”>
<generator class=”native”/>
</id>
</class>

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.

One to One Mapping in Hibernate:

<class name=”Customer” table=” TAB_CUSTOMER”>
<id name=”id” column=”CUSTOMER_ID”>
<generator class=”native”/>
</id>
</class>
<class name=”Address” table=” TAB_ADDRESS”>
<id name=”id” column=”CUSTOMER_ID”>
<generator class=”foreign”>
<param name=”property”>address</param>
</generator>
</id>
<one-to-one name=”address” constrained=”true”/>
</class>

Java:

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

Be the first to comment

Leave a Reply

Your email address will not be published.


*