Junior — Middle
How to implement a one-to-many relationship in a database or object-oriented model?
sobes.tech AI
Answer from AI
A "one-to-many" relationship in a database is implemented using a foreign key in the "many" table that references the primary key of the "one" table.
In an object-oriented model in Java, this is usually implemented as:
public class Parent {
private Long id;
private List<Child> children = new ArrayList<>();
// getters and setters
}
public class Child {
private Long id;
private Parent parent;
// getters and setters
}
If using JPA/Hibernate, the relationship can be described with annotations:
@Entity
public class Parent {
@Id
private Long id;
@OneToMany(mappedBy = "parent")
private List<Child> children;
}
@Entity
public class Child {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
}
Thus, one Parent object can have many associated Child objects.