In a one-to-many relationship, a single entity is associated with multiple instances of another entity. This tutorial will demonstrate how to implement a one-to-many mapping using JPA with an example leveraging EntityManager
.
Example Scenario
Let’s assume the following:
- Department: Represents a department in an organization.
- Employee: Represents employees belonging to a department.
Each department can have multiple employees, but an employee belongs to only one department.
Step-by-Step Implementation
Step 1: Create Entity Classes
- Department Entity
- Employee Entity
Step 2: Persistence Configuration
Configure your persistence.xml
:
Step 3: Using EntityManager
Create a main class to demonstrate the relationship.
Key Points:
Mapping Annotations:
@OneToMany
: Declares the relationship in the parent entity.@ManyToOne
: Declares the relationship in the child entity.@JoinColumn
: Specifies the foreign key in the child table.
Cascade Operations:
CascadeType.ALL
: Ensures that changes (persist, remove, etc.) inDepartment
are cascaded to its employees.
Orphan Removal:
orphanRemoval = true
: Ensures that when anEmployee
is removed from theDepartment
list, it is also deleted from the database.
EntityManager:
- Use
em.persist()
to save theDepartment
, and the relatedEmployee
instances are persisted automatically.
- Use
Comments
Post a Comment