@ManyToOne in JPA: Definition, Usage, and Examples
@ManyToOne in JPA is an annotation that defines a many-to-one relationship between two entities, meaning many instances of one entity relate to one instance of another. It is used to map database foreign key relationships where many records link to a single parent record.How It Works
Imagine you have a group of students and each student belongs to one classroom. Many students can be in the same classroom, but each student only has one classroom. This is what @ManyToOne models in JPA: many objects pointing to one object.
In database terms, the entity with @ManyToOne holds a foreign key that links to the primary key of the related entity. When JPA loads the entity, it fetches the related parent entity automatically or lazily depending on configuration.
This helps keep data organized and connected, just like how a classroom groups many students together.
Example
This example shows a Student entity linked to a Classroom entity using @ManyToOne. Each student belongs to one classroom.
import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; @Entity public class Classroom { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne private Classroom classroom; // getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Classroom getClassroom() { return classroom; } public void setClassroom(Classroom classroom) { this.classroom = classroom; } }
When to Use
Use @ManyToOne when you have a relationship where many records belong to one parent record. For example:
- Many orders belong to one customer.
- Many comments belong to one blog post.
- Many employees belong to one department.
This annotation helps JPA understand how to join tables and fetch related data efficiently.
Key Points
@ManyToOnedefines a many-to-one relationship in JPA entities.- The owning side holds the foreign key in the database.
- It helps model real-world relationships like many students in one classroom.
- Fetch type can be eager or lazy to control loading behavior.
- Often paired with
@OneToManyon the other side for bidirectional mapping.
Key Takeaways
@ManyToOne maps many entities to one parent entity in JPA.@OneToMany for two-way navigation between entities.