In this blog we will go through a use case which will demonstrate one to one relationship,one to many relationship and many to many relationship in Hibernate.Both flavors of one to one relationship will be explained.One to one relationship can be done using shared primary key as well as through foriegn key mapping.
i)Here we are having one to many relationship between department and employee.One department can have many employees.But one employee belongs to one department only.
ii)There is many to many relationship between employee and address.Same address can belong to multiple employees and vice versa.
iii)There is one to one relationship between employee and salary account having shared primary key association between them.
iv)There is one to one relationship between employee and family history with family history containing employee id as foreign key.
Entity relationship diagram shows the relationship.
Department.java having collection of employees.Department is on the non owning side of the relationship.Thats why we have mappedBy attribute on empSet.
Address.java having many to many relationship with employee and on the non owning side of the relationship.Thats why we have mappedBy attribute on empSet.
FamilyHistory.java having one to one relationship with employee with empId as foreign key.We have Join Column annotation stating the column mapping.Since FamilyHistory owns the relationship ,so we donot have mappedBy attribute.
SalaryAcct.java having one to one relationship with employee.Both SalaryAcct and Employee share the same primary key.In SalaryAcct we have created a GenericGenerator with strategy as foreign and using it for id mapping.Moreover on employee property besides One to One Mapping we have one more mapping of PrimaryKeyJoinColumn
Employee.java containing ManytoOne relationship with department,ManytoMany with address,OneToOne with FamilyHistory,OneToOne having shared primary key with salary account.
Here employee is the owner of the many to many relationship with address.But it is on non owning side for one to one relationship with family history and salary account
Testcase for inserting employee information.Here we are creating the objects and associating it as per different types of relationships
Test Case output.Since we were using bidirectional relationship.There is no update query for foreign key values