Unidirectional One-to-Many and Many-to-One using Department and Employee Tables
I'll show you both unidirectional approaches:
-
Unidirectional
@OneToMany
→ TheDepartment
entity knows aboutEmployee
, butEmployee
does NOT know aboutDepartment
. -
Unidirectional
@ManyToOne
→ TheEmployee
entity knows aboutDepartment
, butDepartment
does NOT know aboutEmployee
.
1️⃣ Unidirectional @OneToMany
Entity Definitions
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany
@JoinColumn(name = "department_id") // ✅ Forces FK in Employee instead of a join table
private List<Employee> employees;
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
2️⃣ Unidirectional @ManyToOne
(Recommended)
✅ This is the best practice: The Employee
table has a department_id
column, and Department
does not have a List<Employee>
.
Entity Definitions
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id") // ✅ Foreign key column
private Department department;
}
Generated SQL
This creates only two tables, without an extra join table:
CREATE TABLE department (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE employee (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
department_id BIGINT,
FOREIGN KEY (department_id) REFERENCES department(id)
);
✅ This is better because:
- The foreign key (
department_id
) is stored inside the Employee table. - No extra join table is needed.
- It’s more efficient for querying.
🔥 Conclusion
Approach | Uses @OneToMany ? |
Uses @ManyToOne ? |
Foreign Key in Employee? | Extra Join Table? | Recommended? |
---|---|---|---|---|---|
Unidirectional @OneToMany |
✅ Yes | ❌ No | ❌ No | ✅ Yes | ❌ No |
Unidirectional @ManyToOne |
❌ No | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
🚀 Best practice: Use only @ManyToOne
for a unidirectional relationship.