Monday, 26 December 2022

Hibernate 6: @OneToOne: one to one association

In a one-to-one relationship, each row in one database table is linked to 1 and only 1 other row in another table.

 

For example, there is one to one relationship between employee and employee_details.

 

Types of One to One association

There are two types of one to one association.

a.   Unidirectional one to one association

b.   Bidirectional one to one association

 

Unidirectional one to one association

@Entity
@Table(name = "employee_details")
public class EmployeeDetails {

	@Id
	private int id;

	private String departmentName;

	.........
	.........
}

@Entity
@Table(name = "employee")
public class Employee {
	@Id
	private int id;

	private String name;

	@OneToOne
	@JoinColumn(name = "employee_details_id")
	private EmployeeDetails employeeDetails;

	..........
	..........
}

Above snippet generates below DDL.

create table employee (
       id integer not null,
        name varchar(255),
        employee_details_id integer,
        primary key (id)
    )

    create table employee_details (
       id integer not null,
        departmentName varchar(255),
        primary key (id)
    )

     alter table if exists employee 
       add constraint FKsg6w2kdo2j1t3wt0vxta131it 
       foreign key (employee_details_id) 
       references employee_details

In one to one association, employee is considered as client side and employee_details is considered as parent side. But a much more natural mapping would be employee from parent side and pushing the foreign key to employee_details side. This can be achieved using bidirectional one to one association.

 

Bidirectional one to one association

@Entity
@Table(name = "employee")
public class Employee {
	@Id
	private int id;

	private String name;

	@OneToOne(mappedBy = "emp", 
			cascade = CascadeType.ALL, 
			orphanRemoval = true, 
			fetch = FetchType.LAZY)
	private EmployeeDetails employeeDetails;

	..........
	..........
}

@Entity
@Table(name = "employee_details")
public class EmployeeDetails {

	@Id
	private int id;

	private String departmentName;

	@OneToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "emp_id")
	private Employee emp;

	..........
	..........
}

 

Above snippet generates below DDL.

    create table employee (
       id integer not null,
        name varchar(255),
        primary key (id)
    )

    create table employee_details (
       id integer not null,
        departmentName varchar(255),
        emp_id integer,
        primary key (id)
    )

    alter table if exists employee_details 
       add constraint FKjwhhv402ja2w9ioxfbmbouv 
       foreign key (emp_id) 
       references employee

 

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment