Hibernate Unidirectional One to One Association Mapping
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.
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.
