Relationship Mapping Annotations Flashcards
@OneToOne
Defines a one-to-one relationship between two entities.
import javax.persistence.*;
@Entity
public class User {
@OneToOne
@JoinColumn(name = “profile_id”) // Specifies the foreign key column
private Profile profile; // One-to-one relationship with Profile
import javax.persistence.*;
@Entity
public class Profile {
@OneToOne(mappedBy = “profile”) // The inverse side of the relationship
private User user; // The User related to this Profile
In the Profile entity, the @OneToOne(mappedBy = “profile”) annotation specifies that the Profile is the inverse side of the relationship (i.e., it’s owned by the User entity).
You can now persist and fetch the User and Profile entities using JPA.
When you fetch a User entity, the associated Profile can be retrieved as well.
@OneToMany
In a one-to-many relationship, one entity contains a collection (e.g., a list) of another entity.
@Entity
public class User {
@OneToMany(mappedBy = “user”, cascade = CascadeType.ALL)
private List<Order> orders; // One user can have many orders</Order>
The Order entity is the “many” side of the relationship and will have a reference to the User entity.
@Entity
public class Order {
@ManyToOne
@JoinColumn(name = “user_id”) // Foreign key column
private User user; // Each order is associated with one user
When the User is saved, the related Order entities are saved as well, thanks to the CascadeType.ALL setting in the @OneToMany annotation.
When you fetch a User entity, you can also access the list of related Order entities
@ManyToOne
This is the inverse of the @OneToMany relationship, where one entity can have many related entities.
@ManyToMany
The @ManyToMany annotation in JPA is used to define a many-to-many relationship, where multiple instances of one entity can be associated with multiple instances of another entity. This relationship is symmetrical, meaning both entities can have many instances of each other.
@Entity
public class Student {
@ManyToMany
@JoinTable(
name = “student_course”,
joinColumns = @JoinColumn(name = “student_id”),
inverseJoinColumns = @JoinColumn(name = “course_id”)
)
private Set<Course> courses; // Many students can be enrolled in many courses</Course>
@Entity
public class Course {
@ManyToMany(mappedBy = “courses”) // The inverse side of the relationship
private Set<Student> students; // Many students can be enrolled in many courses</Student>
The mappedBy attribute in the Course entity indicates that the Student entity is the owner of the relationship (i.e., the @JoinTable is defined on the Student side). Thus, no @JoinTable annotation is needed in the Course entity.
You also need the join table in your database student_course
@Fetch
Defines how related entities are fetched (eager vs lazy loading).
@ManyToOne(fetch = FetchType.LAZY)
private Address address;