Steps to Implement One-to-Many Mapping
1. Define the Entities:
Start by the creating java classes for the entities involved in the relationship. Here the below example for entity classes for Department and Employee.
// Department Entity
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
// Getters and Setters
}
// Employee Entity
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and Setters
}
2. Establish Relationship:
We can annotate with the appropriate fields in the entities to establish the one to many relationship. In Department entity, use the @OneToMany can indicates the relationship with the Employee entity and the Employee entity can use the @ManyToOne to indicates the relationship back to Department Entity.
3. Implement Persistence:
We can utilize the JPA annotation and it can configuration to the persist the entites and their relationships. Ensure the proper setup of the database connection and the persistence unit configuration in the persistence.xml file of the JPA application.
4. Test the Mapping:
We can execute the code to verify the correctness of the mapping and the relationships. Below Example can demonstrating the creation of the department and associated with the multiple Employees with it.
// Test class to demonstrate one-to-many mapping
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("example");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// Creating Department
Department department = new Department();
department.setName("Engineering");
// Creating Employees
Employee emp1 = new Employee();
emp1.setName("Mukesh");
emp1.setDepartment(department);
Employee emp2 = new Employee();
emp2.setName("Smith");
emp2.setDepartment(department);
department.getEmployees().add(emp1);
department.getEmployees().add(emp2);
em.persist(department);
em.getTransaction().commit();
em.close();
emf.close();
}
}
We can execute the code then creates the Department Engineering and it can associates with two Employees with it. It can demonstrating the functionality of the one to many mapping.
JPA – One-to-Many Mapping
In Java Persistence API(JPA), JPA can serve as the fundamental tool for Java developers to interact with databases in an object-oriented manner. Among the many features it can offer One-to-many mapping is the crucial concept that can used to establish the relationships between the entities in the database.