Spring Boot applications leverage JPA (Java Persistence API) with Hibernate as the default implementation to manage relationships between entities. Here are examples for one-to-one, one-to-many, and many-to-many relationships:
1. One-to-One Relationship
A one-to-one relationship implies that one instance of an entity is associated with exactly one instance of another entity.
Example:
User and UserProfile2. One-to-Many / Many-to-One Relationship
A one-to-many relationship means one entity can be associated with multiple instances of another entity. The inverse is a many-to-one relationship.
Example:
Department and Employee3. Many-to-Many Relationship
A many-to-many relationship indicates that multiple instances of one entity can be associated with multiple instances of another entity. This is typically managed through a join table.
Example:
Student and CourseKey Annotations and Concepts:
@Entity: Marks a class as a JPA entity, mapping it to a database table.@Id: Designates the primary key of an entity.@GeneratedValue: Configures the primary key generation strategy.@OneToOne,@OneToMany,@ManyToOne,@ManyToMany: Define the type of relationship.@JoinColumn: Specifies the foreign key column in the owning side of the relationship.mappedBy: Used on the inverse side of a bidirectional relationship to indicate the field in the owning entity that manages the relationship.@JoinTable: Used in many-to-many relationships to define the join table and its columns.CascadeType: Specifies how persistence operations (e.g., persist, merge, remove) should cascade from one entity to its related entities.orphanRemoval: When set totruewith@OneToMany, it automatically removes child entities from the database when they are no longer referenced by the parent.
ไม่มีความคิดเห็น:
Thank you