Sobes.tech
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:

  • @OneToMany indicates that one author is related to many books.
  • mappedBy specifies the field in the Book entity that owns the relationship (usually a field with the @ManyToOne annotation).

Mechanism:

  • The relationship in the database is implemented via a foreign key in the "many" table (for example, in the Book table, there will be an author_id column).
  • 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.