Entity Mappings
Relational databases structure massive data sets by assigning rows explicitly across different tables, connecting them utilizing Foreign Keys.
In JPA, developers configure these structural relations inside the Java Entity objects utilizing mapping annotations.
1. One-to-One
A strict relationship where exactly one database row corresponds to a single distinct row.
@Entity
public class User {
@Id @GeneratedValue
private Long id;
// This assigns the Foreign Key internally
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "passport_id")
private Passport passport;
}
2. One-to-Many / Many-to-One
A single Department (One) logically maps to multiple Employees (Many).
@Entity
public class Department {
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Entity
public class Employee {
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}
3. Many-to-Many
Multiple Students logically mapping internally to multiple Courses.
@Entity
public class Student {
@ManyToMany
@JoinTable(
name = "student_courses", // The bridge table
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private List<Course> courses;
}