Relationship Inspector
Select a relationship type from the top menu to see how Java Objects are mapped to Database Tables.
Key Concepts
Understanding JPA Entity Relationships
The core challenge of an ORM (Object-Relational Mapper) like Hibernate is resolving the Object-Relational Impedance Mismatch. Java uses Objects and References (Lists, Sets) to represent relationships. Databases use Tables and Foreign Keys. JPA annotations bridge this gap.
The "Owning Side" Concept
In a bidirectional relationship, one entity must be the "owner". The
owning side is the entity that has the underlying Foreign Key column in its database
table. The other side is the "inverse" side and must use the mappedBy
attribute.
1. @OneToOne
Used when exactly one instance of Entity A is associated with exactly one instance of Entity B (e.g., User and UserProfile).
@Entity
public class User {
@Id private Long id;
// User is the OWNER (contains the FK)
@OneToOne
@JoinColumn(name = "profile_id")
private Profile profile;
}
@Entity
public class Profile {
@Id private Long id;
// Inverse side. Does NOT have the FK.
@OneToOne(mappedBy = "profile")
private User user;
}
2. @OneToMany & @ManyToOne
The most common relationship. For example, one Department has many Employees. Rule of thumb: The @ManyToOne side is almost always the owning side because relational databases put the Foreign Key on the "Many" table.
@Entity
public class Employee {
@Id private Long id;
// Employee is the OWNER (FK in DB)
@ManyToOne
@JoinColumn(name = "dept_id")
private Department department;
}
@Entity
public class Department {
@Id private Long id;
// Inverse side. Uses a Collection.
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
3. @ManyToMany
Used when multiple instances of Entity A can be related to multiple instances of Entity B (e.g., Students and Courses). Relational databases cannot represent this directly; they require a third "Join Table".
@Entity
public class Student {
@Id private Long id;
// Student owns the relationship
@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses;
}
@Entity
public class Course {
@Id private Long id;
// Inverse side
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
}