Junior — Middle
Can you explain how the @OneToMany annotation works in ORM and table relationships?
sobes.tech AI
Answer from AI
The @OneToMany annotation in ORM (for example, in JPA/Hibernate) is used to denote a "one-to-many" relationship between two entities. This means that one object (entity) is associated with many other objects.
For example, you have an entity Author and an entity Book. One author can have many books. In the Author class, you might write:
@OneToMany(mappedBy = "author")
private List<Book> books;
Here:
@OneToManyindicates that one author is related to many books.mappedByspecifies the field in theBookentity that owns the relationship (usually a field with the@ManyToOneannotation).
Mechanism:
- The relationship in the database is implemented via a foreign key in the "many" table (for example, in the
Booktable, there will be anauthor_idcolumn). - The ORM automatically loads the collection of related objects when needed.
- You can configure cascade operations and fetch strategies (lazy or eager loading).
Thus, @OneToMany helps describe and manage relationships between tables at the object level.