The @ManyToOne annotation helps connect two data tables where many items belong to one main item. It makes managing related data easier.
0
0
@ManyToOne relationship in Spring Boot
Introduction
When you have many orders that belong to one customer.
When many comments belong to one blog post.
When many employees work in one department.
When many books are written by one author.
Syntax
Spring Boot
@ManyToOne
@JoinColumn(name = "column_name")
private EntityType entity;@ManyToOne marks the many side of the relationship.
@JoinColumn sets the database column that links the two tables.
Examples
Many orders belong to one customer, linked by customer_id.
Spring Boot
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;Many employees belong to one department, linked by department_id.
Spring Boot
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;Sample Program
This example shows two classes: Order and Customer. Many orders can belong to one customer. The @ManyToOne annotation links each order to its customer. When we print, we see the order's product and the customer's name.
Spring Boot
import jakarta.persistence.*; @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String product; @ManyToOne @JoinColumn(name = "customer_id") private Customer customer; // Constructors, getters, setters public Order() {} public Order(String product, Customer customer) { this.product = product; this.customer = customer; } public Long getId() { return id; } public String getProduct() { return product; } public Customer getCustomer() { return customer; } public void setProduct(String product) { this.product = product; } public void setCustomer(Customer customer) { this.customer = customer; } } @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // Constructors, getters, setters public Customer() {} public Customer(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // Example usage in a service or main method public class Example { public static void main(String[] args) { Customer customer = new Customer("Alice"); Order order = new Order("Book", customer); System.out.println("Order product: " + order.getProduct()); System.out.println("Order belongs to customer: " + order.getCustomer().getName()); } }
OutputSuccess
Important Notes
Always set @JoinColumn to specify the foreign key column in the database.
@ManyToOne is the most common way to model many items linked to one item.
Remember to have getters and setters for JPA to work properly.
Summary
@ManyToOne connects many objects to one object in the database.
Use @JoinColumn to name the linking column.
This helps keep related data organized and easy to access.