Can you explain how relationships between entities are established and managed in ORM or databases?
sobes.tech AI
Answer from AI
In ORM (Object-Relational Mapping), relationships between entities are established through annotations or configurations that describe the type of relationship: one-to-one (OneToOne), one-to-many (OneToMany), many-to-one (ManyToOne), and many-to-many (ManyToMany).
For example, in Java using JPA/Hibernate, relationships are defined as follows:
@Entity
public class Author {
@Id
private Long id;
@OneToMany(mappedBy = "author")
private List<Book> books;
}
@Entity
public class Book {
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
}
Here, Author and Book are linked by a one-to-many relationship. ORM manages these relationships by creating the corresponding foreign keys in the database and ensuring the loading of related objects when necessary (lazy or eager loading).
Managing relationships includes:
- Defining the owner of the relationship (for example,
mappedByindicates that the relationship is managed on the other side). - Cascade operations, so changes in one entity are reflected in related entities.
- Configuring fetch type for performance optimization.
Thus, ORM abstracts the work with foreign keys and allows working with objects and their relationships at the code level.