How to Implement Database Relationship in Hibernate?

Hibernate supports several types of database relationships, including one-to-one, one-to-many, many-to-one, and many-to-many relationships. These relationships can be implemented in Hibernate by using annotations or XML mapping files.

Types of Database Relationships

  • One-to-One Relationship
  • One-to-Many Relationship
  • Many-to-One Relationship
  • Many-to-Many Relationship

1. One-to-One Relationship: To implement a one-to-one relationship in Hibernate, we can use the @OneToOne annotation on the primary key side of the relationship. The join column is specified using the @JoinColumn annotation.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToOne
@JoinColumn(name = "address_id")
private Address address;
}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String street;
private String city;
private String state;
}

2. One-to-Many Relationship: To implement a one-to-many relationship in Hibernate, we can use the @OneToMany annotation on the many side of the relationship. The mappedBy attribute specifies the inverse side of the relationship.

Example:

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToMany(mappedBy = "department")
private List employees;
}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}

3. Many-to-One Relationship: To implement a many-to-one relationship in Hibernate, we can use the @ManyToOne annotation on the many side of the relationship. The join column is specified using the @JoinColumn annotation.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@OneToMany(mappedBy = "department")
private List employees;
}

4. Many-to-Many Relationship: To implement a many-to-many relationship in Hibernate, we can use the @ManyToMany annotation. A join table is required to map the relationship.

Example:

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "employee_project",
joinColumns = { @JoinColumn

BY Best Interview Question ON 10 Feb 2023