flowchart TD
START["Define Association between Entity A and Entity B"] --> CARD{"What is the Cardinality?"}
CARD -->|"One-to-One (1:1)"| OTO{"Are entities tightly coupled composites?"}
OTO -->|"Yes (e.g. Instructor -> Detail)"| OTO_ALL["CascadeType.ALL on Owning Side<br/>Selective Cascades on Inverse Side"]
OTO -->|"No (Independent Lifecycles)"| OTO_SEL["Selective: PERSIST, MERGE, REFRESH, DETACH<br/>(Exclude REMOVE)"]
CARD -->|"One-to-Many (1:N)"| OTM{"Does Child have meaning without Parent?"}
OTM -->|"No (e.g. Course -> Reviews)"| OTM_ALL["1:N Unidirectional<br/>CascadeType.ALL + @JoinColumn"]
OTM -->|"Yes (e.g. Instructor <-> Course)"| OTM_SEL["1:N Bidirectional with mappedBy<br/>Selective Cascades (Exclude REMOVE)<br/>Programmatic Dissociation on Delete"]
CARD -->|"Many-to-Many (M:N)"| MTM["@ManyToMany via @JoinTable<br/>NEVER USE CascadeType.REMOVE<br/>Peers must have independent lifecycles"]
3. Fetch Strategy Comparison: Default Rules vs JOIN FETCH¶
// Single Collection Fetch"SELECT i FROM Instructor i JOIN FETCH i.courses WHERE i.id = :id"// Multiple Joins (1:1 + 1:N)"SELECT i FROM Instructor i JOIN FETCH i.courses JOIN FETCH i.instructorDetail WHERE i.id = :id"// Left Outer Join Fetch (includes Instructors with ZERO courses)"SELECT i FROM Instructor i LEFT JOIN FETCH i.courses WHERE i.id = :id"
When deleting entities that participate in associations without cascading removal, follow the Dissociation Protocol to avoid foreign key constraint failures:
sequenceDiagram
autonumber
participant Service as Business Service
participant DAO as Data Access Object
participant EM as EntityManager
participant DB as Relational Database
Service->>DAO: deleteInstructor(instructorId)
DAO->>EM: find(Instructor.class, instructorId)
EM->>DB: SELECT * FROM instructor WHERE id=?
DB-->>EM: Instructor (Managed)
Note over DAO: Step 1: Programmatic Dissociation
loop For each Course in instructor.getCourses()
DAO->>DAO: course.setInstructor(null)
end
Note over DAO: Step 2: Entity Removal
DAO->>EM: remove(instructor)
Note over EM,DB: Flush: Flushes FK updates before DELETE
EM->>DB: UPDATE course SET instructor_id=NULL WHERE id=?
EM->>DB: DELETE FROM instructor WHERE id=?
DB-->>EM: Success
1:N Parent Deletion (Instructor preserving Courses):
for (Course c : instructor.getCourses()) { c.setInstructor(null); }entityManager.remove(instructor);
M:N Inverse Deletion (Student preserving Courses):
for (Course c : student.getCourses()) { c.getStudents().remove(student); }entityManager.remove(student);