Real data is related: a course has many enrollments, and each enrollment belongs to one course. JPA and Hibernate map these relationships to foreign keys so you can work with objects instead of join queries. Getting the mapping right avoids some of the most common Spring Boot bugs.
The many side: @ManyToOne
@Entity
public class Enrollment {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
private Course course;
}
This creates a course_id foreign key column in the enrollment table. The many side is the owning side: it controls the foreign key.
The one side: @OneToMany
@Entity
public class Course {
@Id @GeneratedValue private Long id;
@OneToMany(mappedBy = "course")
private List<Enrollment> enrollments = new ArrayList<>();
}
mappedBy says “the foreign key is managed by the course field in Enrollment”. Without it, Hibernate creates an unnecessary join table.
Fetch types
- LAZY: related data loads only when you access it. Prefer it for most relationships.
- EAGER: related data always loads, which can pull far more data than you need.
Lazy loading outside a transaction causes the famous LazyInitializationException. Load what you need inside the service method, for example with a fetch join query or an entity graph.
Common bugs
- N+1 queries: looping over courses and touching each course’s enrollments triggers one query per course. Use
JOIN FETCHin a repository query. - Infinite JSON recursion: returning entities with two-way relationships from a REST API loops forever. Return DTOs or records instead.
- Forgetting to set both sides in memory when adding a child; write a helper method that updates both.
Related: Hibernate and JPA explained, Spring Boot with MySQL and Java records.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
