Home One-To-Many Relationship
Post
Cancel

One-To-Many Relationship

One-To-Many Relationship:

A One-To-Many relationship is a unidirectional relationship between two entities, where one entity is the owner of the relationship and the other entity is the dependent. In this relationship, one entity can have multiple instances of the other entity, but the dependent entity can only belong to one owner.

Consider a simple application that manages departments and employees in an organization. Each department has a name and a set of employees, while each employee has a name and a salary. One-To-Many Relationship: The Department entity would have the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Entity
public class Department {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  @JoinColumn(name = "department_id")
  private Set<Employee> employees = new HashSet<>();

  // constructor, getters and setters
}

The Employee entity would have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  private double salary;

  // constructor, getters and setters
}

In this example, the Department entity has a One-To-Many relationship with the Employee entity. The @OneToMany annotation on the Department entity specifies the target entity as the Employee entity and the fetch type as LAZY. This means that the relationship will be loaded only when it is explicitly accessed.

Visual Data

Department Table

idname
1IT
2Finance

Employee Table

idnamedepartment_id
1John1
2Jane1
3Mark2

FetchType

In JPA, One-To-Many relationships can be either eagerly or lazily loaded. Eager loading means that the relationship is loaded when the parent entity is loaded, while lazy loading means that the relationship is loaded only when it is explicitly accessed.

Conclusion

In conclusion, One-To-Many relationships are fundamental concepts in JPA, and understanding these relationships is crucial for designing and implementing relational databases in Java applications. With JPA, these relationships can be easily mapped and managed, providing a powerful tool for data persistence in Java development.

This post is licensed under CC BY 4.0 by the author.