Entity Relationships
Real data is connected: a project has many tasks, a task belongs to one project, tasks have many tags. JPA maps these with @ManyToOne, @OneToMany, @OneToOne and @ManyToMany. Getting the mapping right — especially which side owns the foreign key and when related data is loaded — decides whether your API makes 2 SQL queries or 200.
Many-to-one: the most common relationship
Each task belongs to one project. The tasks table gets a project_id foreign key:
@Entity
public class Task {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "project_id")
private Project project;
...
}One-to-many: the other side
@Entity
public class Project {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Task> tasks = new ArrayList<>();
public void addTask(Task task) { // keep both sides in sync
tasks.add(task);
task.setProject(this);
}
public void removeTask(Task task) {
tasks.remove(task);
task.setProject(null);
}
}| Concept | Meaning |
|---|---|
| owning side | the side with the foreign key (Task.project, @JoinColumn). Only changes here are written to the DB |
mappedBy = "project" |
marks the inverse side; it just mirrors the owning side |
cascade = ALL |
saving/deleting the project also saves/deletes its tasks |
orphanRemoval = true |
a task removed from the list is deleted |
| helper methods | update both sides so the in-memory graph matches the database |
The relationship annotations
| Annotation | Example | Default fetch |
|---|---|---|
@ManyToOne |
task → project | EAGER (set it to LAZY!) |
@OneToMany |
project → tasks | LAZY |
@OneToOne |
user → profile | EAGER |
@ManyToMany |
task ↔ tags (join table) | LAZY |
Tip: Make every
@ManyToOneand@OneToOnefetch = FetchType.LAZY, then load related data explicitly when a use case needs it. Eager defaults load data you didn't ask for, on every query.
The N+1 query problem
Listing 3 projects and the number of tasks in each looks innocent:
for (Project p : projectRepository.findAll()) {
System.out.println(p.getName() + ": " + p.getTasks().size()); // lazy load per project!
}That runs 1 query for projects plus N queries for their tasks. This simulation counts the queries for both strategies:
import java.util.*;
class Db {
int queries = 0;
final Map<Long, String> projects = new TreeMap<>(Map.of(1L, "Website", 2L, "Mobile app", 3L, "Docs"));
final Map<Long, List<String>> tasksByProject = Map.of(
1L, List.of("Landing page", "Pricing page"),
2L, List.of("Login screen"),
3L, List.of("API guide", "FAQ", "Changelog"));
Map<Long, String> selectProjects() {
queries++;
System.out.println(" SQL: select * from project");
return projects;
}
List<String> selectTasksOf(long projectId) {
queries++;
System.out.println(" SQL: select * from task where project_id=" + projectId);
return tasksByProject.get(projectId);
}
Map<Long, List<String>> selectProjectsJoinTasks() {
queries++;
System.out.println(" SQL: select p.*, t.* from project p left join task t on t.project_id=p.id");
return tasksByProject;
}
}
class Main {
public static void main(String[] args) {
Db db = new Db();
System.out.println("Lazy loading in a loop:");
for (var p : db.selectProjects().entrySet()) {
System.out.println(" " + p.getValue() + ": " + db.selectTasksOf(p.getKey()).size());
}
System.out.println(" -> " + db.queries + " queries");
Db db2 = new Db();
System.out.println("Join fetch:");
Map<Long, List<String>> all = db2.selectProjectsJoinTasks();
for (var p : db2.projects.entrySet()) {
System.out.println(" " + p.getValue() + ": " + all.get(p.getKey()).size());
}
System.out.println(" -> " + db2.queries + " query");
}
}Lazy loading in a loop:
SQL: select * from project
SQL: select * from task where project_id=1
Website: 2
SQL: select * from task where project_id=2
Mobile app: 1
SQL: select * from task where project_id=3
Docs: 3
-> 4 queries
Join fetch:
SQL: select p.*, t.* from project p left join task t on t.project_id=p.id
Website: 2
Mobile app: 1
Docs: 3
-> 1 query
With 500 projects the first version issues 501 queries. Fix it by fetching what the use case needs in one query:
public interface ProjectRepository extends JpaRepository<Project, Long> {
@Query("select distinct p from Project p left join fetch p.tasks")
List<Project> findAllWithTasks();
@EntityGraph(attributePaths = "tasks") // same effect, declarative
Optional<Project> findWithTasksById(Long id);
}Or, often best, a projection that only counts:
@Query("select new com.example.tasks.project.ProjectStats(p.name, count(t)) " +
"from Project p left join p.tasks t group by p.name order by p.name")
List<ProjectStats> stats();LazyInitializationException
Lazy associations can only be loaded while the persistence context is open. Accessing project.getTasks() after the transaction ended throws:
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/api/projects/1500
The server log shows the cause:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.tasks.project.Project.tasks: could not initialize proxy - no SessionSpring Boot enables open-in-view by default (and logs a warning about it), which keeps the session open during JSON rendering and hides this error — at the cost of surprise queries in the web layer. Many teams set spring.jpa.open-in-view=false and map entities to DTOs inside the transactional service, using fetch joins where needed.
Many-to-many
@ManyToMany
@JoinTable(name = "task_tags",
joinColumns = @JoinColumn(name = "task_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private Set<Tag> tags = new HashSet<>();Use a Set, not a List, for many-to-many collections. If the link itself needs data (e.g. "added at", "added by"), model it as its own entity with two @ManyToOnes instead.
Test yourself
Which side of a bidirectional one-to-many relationship owns the foreign key?
- The
@OneToManyside withmappedBy - The
@ManyToOneside - Both
- Neither; a join table is always used
You load 100 orders, then access order.getCustomer() lazily for each. How many queries run without a fetch join?
- 1
- 2
- Up to 101
- 100
What is the default fetch type of @ManyToOne?
- LAZY
- EAGER
- NONE
- It depends on the database