MODULE 3 · TOPIC 3 · VISUAL JPA & HIBERNATE LAB

Establishing Relationships with JPA and Hibernate

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.

1. One-to-many / many-to-one — owning side

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.

Java / JPA code
SQL / simulation outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Why this step happens
See all steps in this scenario

    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.

    What this animation explains

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

    Try and observe

    Try only inverse collection and inspect NULL keys. Compare with both sides linked.

    2. One-to-one — uniqueness and database constraints

    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.

    Java / JPA code
    SQL / simulation outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected
    Why this step happens
    See all steps in this scenario

      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.

      What this animation explains

      Database uniqueness prevents violating a one-to-one relationship.

      Try and observe

      Reuse profile #10 with uniqueness enforced; compare the invalid schema without it.

      3. Many-to-many — join table and unlinking

      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.

      Java / JPA code
      SQL / simulation outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected
      Why this step happens
      See all steps in this scenario

        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.

        What this animation explains

        A many-to-many relation is a separate relational structure, not a duplicated course record.

        Try and observe

        Remove course 10 from student 101 and notice student 102 remains linked.

        4. Cascade PERSIST — propagate entity lifecycle

        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.

        Java / JPA code
        SQL / simulation outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected
        Why this step happens
        See all steps in this scenario

          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.

          What this animation explains

          Propagation applies to specific entity lifecycle operations, not arbitrary object references.

          Try and observe

          Compare a managed child without cascade with a new child without cascade.

          5. Orphan removal — relationship versus row deletion

          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.

          Java / JPA code
          SQL / simulation outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected
          Why this step happens
          See all steps in this scenario

            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.

            What this animation explains

            Removing a child from a collection is not always a SQL DELETE.

            Try and observe

            Compare the final line_item rows with orphan removal enabled and disabled.

            6. Fetch strategy — lazy access and N+1 queries

            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.

            Java / JPA code
            SQL / simulation outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected
            Why this step happens
            See all steps in this scenario

              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.

              What this animation explains

              A small data set can hide costly repeated queries.

              Try and observe

              Set four departments, compare separate lazy loads versus JOIN FETCH.

              API and configuration reference

              Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.

              API / settingWhy and when to use it
              @ManyToOneMany child entities refer to one parent
              @OneToMany(mappedBy="department")Inverse collection; points to the owning field
              @OneToOneSingle-valued association with uniqueness constraint
              @ManyToMany / @JoinTableAssociation through a linking table
              cascade=PERSISTPropagate persist to referenced new entities
              orphanRemoval=trueRemove a privately owned child when disassociated

              Worked practical examples

              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.

              1. Map a bidirectional department and student

              Procedure

              1. Extend the Student entity with Department department and replace the class mapping as needed.
              2. Add Department.java with an assigned ID and register both entities in the persistence unit.
              3. Create the department and student, set both sides and persist them within one transaction.
              Code / configuration
              // 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);
              Expected result: student.department_id refers to department.id; the owning Student reference controls the FK.

              2. Map a many-to-many course enrollment

              Procedure

              1. Create Course as an entity with @Id Long id and a public or protected no-arg constructor.
              2. Add the owning collection to Student and persist both new entities before linking.
              3. Commit and inspect the student_course table. Unlink a course in a subsequent transaction.
              Code / configuration
              // 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);
              Expected result: The join table links IDs; unlinking the association does not delete the Course entity.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Which side writes the department foreign key?

              The Student owning side, mapped with @ManyToOne and @JoinColumn.

              2. Does cascade determine whether data is fetched?

              No. Cascade propagates lifecycle operations; fetch controls when related data is loaded.

              3. Why avoid REMOVE for shared courses?

              A course may be used by other students; deleting it is not the same as unlinking enrollment.

              Hands-on practice and assessment

              Programming challenge

              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.

              Quick assessment

              Key points and real Hibernate notes

              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.