Tutorial describes One to One Mappings in JPA with examples.
What are One to One Mappings
One to One mappings between entities refers to those relationships where one record of an entity(say entity-1) is mapped exactly to one record of another entity(say entity-2). Then entity-1 and entity-2 are said to be in a One to One relationship with each other. Or, it can be said that a One to One mapping exists between the two entities.
Example Database Table Structure with a One to One Mapping
An apt scenario for this would be the relation between an employee of a company and the car parking slot that he is assigned to park his vehicle. Both have a one-to-one mapping with each other.
Lets say we have two entities Employee and ParkingSlot represented by equivalent tables EMPLOYEE and PARKING_SLOT in the database schema.
The table structures for EMPLOYEE and PARKING_SLOT tables are as below:
How JPA takes care of one-to-one mappings
For explaining the JPA way of implementing One to One Mappings I will use the EMPLOYEE and PARKING SLOT relation defined above.
The annotation defined by JPA for one-to-one mappings is ‘
@OneToOne’. In the table structure above the PARKING_SLOT_ID foreign key is in EMPLOYEE table. This makes the EMPLOYEE table as the owner of the relationship and hence the
@JoinColumn definition will need to be placed in the employee table along with the
@OnetoOne annotation as shown below in the POJO definition for Employee entity –
In the above code OneToOne mapping has been defined from the
Employeeentity to the
ParkingSlotentity using the
@OneToOneannotation and the
@JoinColumnannotation defines the join column i.e. the column which stores the foriegn key to the PARKING_SLOT table as PARKING_SLOT_ID.
Definition for parking slot POJO entity
The definition for parking slot POJO entity is as follows –
Bi-Directional One-To-One mappings
The one-to-one mapping defined above is actually unidirectional with EMPLOYEE table as the owner of the relationship. Now suppose we want the parking slot also to maintain the reference to the employee that is using the parking slot in order to make the relationship bidirectional.I.e. we need to add a foreign key to EMPLOYEE table in the PARKING_SLOT table. The PARKING_SLOT table would then look like –
The ParkingSlot POJO entity with the newly added reference to Employee entity
@OneToOneforeign key defined to ParkingSlot table.
In this tutorial we looked at what are One to One Mappings(or relationships), an example database table structure with One to One relationships between its tables, how JPA will implement this One to One Mapping in terms of Java POJOs and finally we looked at how to make the JPA implementation bi-directional. This concludes the tutorial on One to One Mappings in JPA.