Sobes.tech
Junior

Provide an example of a 'one-to-many' relationship in the context of databases.

sobes.tech AI

Answer from AI

The One-to-Many relationship in the context of databases means that one record in one table is related to many records in another table.

A typical example: Department and Employees.

  • One department can have many employees.
  • Each employee belongs to exactly one department.

The "Departments" table may contain:

ID Name
1 Sales
2 Development

The "Employees" table may contain:

ID First Name Last Name department_id
101 Ivan Petrov 1
102 Maria Sidorova 1
103 Alexey Ivanov 2

In this example, department_id in the "Employees" table is a foreign key referencing ID in the "Departments" table. This implements a One-to-Many relationship.

In ORM, such as Hibernate/JPA, this relationship can be represented as follows:

// Class representing the Department entity
@Entity
public class Department {

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

    private String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) // One-to-Many relationship with Employee
    private List<Employee> employees;

    // getters and setters
}
// Class representing the Employee entity
@Entity
public class Employee {

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

    private String firstName;
    private String lastName;

    @ManyToOne // Many-to-One relationship with Department (inverse side of One-to-Many)
    @JoinColumn(name = "department_id") // Specifies the foreign key column in Employee table
    private Department department;

    // getters and setters
}

Here, @OneToMany in Department indicates the "one department to many employees" relationship, and mappedBy = "department" indicates that the management of this relationship is on the Employee side through the department field. @ManyToOne in Employee is the inverse side of the relationship. @JoinColumn specifies the foreign key column.

Provide an example of a 'one-to-many' relationship in… - sobes.tech