What this animation explains
Cardinality and ownership are different: the many-to-one side owns this mapping.

MODULE 3 · TOPIC 3 · VISUAL JPA & HIBERNATE LAB
Relational associations connect tables with primary keys, foreign keys and join tables. JPA maps those links to object references and collections. Cardinality, owning side, fetch strategy and cascade rules determine how the object graph is loaded and saved. This topic distinguishes Java-side links from database constraints and demonstrates each association with changing rows.
Browser-based JPA and Hibernate simulations. Change inputs and trace entity state, SQL, database rows and transactions. No real Java or database operations are executed.
A department may contain many students while a student belongs to one department. The foreign key normally lives in the student table. In a bidirectional mapping mappedBy marks the inverse collection; update the owning many-to-one reference and both Java-side collections consistently.
Why this example? Choose the number of students and whether the owner is set; inspect which foreign keys are written.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Cardinality and ownership are different: the many-to-one side owns this mapping.
Try only inverse collection and inspect NULL keys. Compare with both sides linked.
One-to-one maps a single related object. A unique foreign key or shared primary key enforces the intended relational cardinality. An object annotation alone cannot repair missing constraints in an existing schema. This lab models the actual database constraint separately.
Why this example? Try linking two students to the same profile with and without a unique FK.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Database uniqueness prevents violating a one-to-one relationship.
Reuse profile #10 with uniqueness enforced; compare the invalid schema without it.
Many students can enroll in many courses. A join table stores pairs of foreign keys; a composite uniqueness rule prevents duplicate pairs. Removing a link should not delete a shared course. The owning collection controls changes to the join table.
Why this example? Add or remove links for course 10 or 20 and compare the table before and after.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
A many-to-many relation is a separate relational structure, not a duplicated course record.
Remove course 10 from student 101 and notice student 102 remains linked.
Cascade PERSIST makes persistence operations reach related new entities. It is not database ON DELETE CASCADE or eager fetching. Without cascade, explicitly persist new children before flushing a relationship that references them.
Why this example? Change cascade and child lifecycle state to see when persistence succeeds.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Propagation applies to specific entity lifecycle operations, not arbitrary object references.
Compare a managed child without cascade with a new child without cascade.
orphanRemoval on OneToOne or OneToMany is meant for privately owned dependents. Disassociating a managed child can schedule its deletion. Without orphan removal, a nullable owning FK may simply become null when both sides are synchronized. Shared many-to-many targets are different.
Why this example? Change orphan removal and disassociate or keep an order line item.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Removing a child from a collection is not always a SQL DELETE.
Compare the final line_item rows with orphan removal enabled and disabled.
Lazy associations may load only when accessed; eager loading means state must be available, not necessarily one SQL join. A fetch join can explicitly load selected associations. N+1 appears when a list query is followed by separate lazy loads for every parent.
Why this example? Vary parent count and fetch strategy to compare total SQL requests.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
A small data set can hide costly repeated queries.
Set four departments, compare separate lazy loads versus JOIN FETCH.
Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.
| API / setting | Why and when to use it |
|---|---|
| @ManyToOne | Many child entities refer to one parent |
| @OneToMany(mappedBy="department") | Inverse collection; points to the owning field |
| @OneToOne | Single-valued association with uniqueness constraint |
| @ManyToMany / @JoinTable | Association through a linking table |
| cascade=PERSIST | Propagate persist to referenced new entities |
| orphanRemoval=true | Remove a privately owned child when disassociated |
Follow these procedures with the Jakarta Persistence 3.1 / Hibernate ORM 6.6 teaching project. Snippets require the indicated entities and an open EntityManager; SQL varies by dialect.
// Department.java (fields inside @Entity class Department) @Id Long id; @OneToMany(mappedBy="department") List<Student> students = new ArrayList<>(); // Student.java (field inside @Entity class Student) @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="department_id") Department department; // In an active transaction: s.department=d; d.students.add(s); em.persist(d); em.persist(s);
// Inside Student entity @ManyToMany @JoinTable(name="student_course", joinColumns=@JoinColumn(name="student_id"), inverseJoinColumns=@JoinColumn(name="course_id")) Set<Course> courses=new HashSet<>(); // In active transaction with managed s and c: s.courses.add(c); // Later, another transaction: s.courses.remove(c);
Try answering these questions, then expand each answer and repeat the appropriate simulation.
The Student owning side, mapped with @ManyToOne and @JoinColumn.
No. Cascade propagates lifecycle operations; fetch controls when related data is loaded.
A course may be used by other students; deleting it is not the same as unlinking enrollment.
Add Department, Course and enrollment mappings in a fresh copy of the H2 project. Register all new entities in persistence.xml. Persist both sides, then examine foreign keys, join tables and generated SQL.
Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.
The examples assume mapped entity classes with IDs and no-arg constructors. Use helper methods to keep both sides of bidirectional relationships consistent. Never cascade REMOVE indiscriminately to shared entities.