MODULE 3 · TOPIC 1 · VISUAL JPA & HIBERNATE LAB

Introduction to JPA and Hibernate

Jakarta Persistence (JPA) defines the contract for mapping Java objects to relational data. Hibernate ORM implements that contract and uses JDBC drivers to talk to the database. A persistence unit supplies mapping and connection settings; an EntityManager owns a persistence context that tracks entity identity and changes. Learn how metadata, SQL, transactions and object state cooperate from startup to commit. This course uses Java 21, Jakarta Persistence 3.1 and Hibernate ORM 6.6 as a fixed teaching baseline.

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. ORM architecture — Java to relational database

Object-relational mapping translates fields and object identity into columns and keys. JPA supplies the API; Hibernate interprets the mapping, chooses SQL and delegates to a JDBC driver. The database enforces constraints and transaction semantics. A read can also be served from a persistence context instead of SQL; this lab assumes an initially empty context.

Why this example? Select a database and a read or write operation to trace each layer and inspect the corresponding database rows.

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

    The Java API remains stable while URL, driver and dialect change.

    Try and observe

    Switch H2 to MySQL, then change find to persist. Follow the data through the driver and database cylinder.

    2. Entity mapping — class fields become columns

    An entity is a persistent Java class with an identity. Field access is determined by where the identifier annotation is placed unless explicitly overridden. Column names, constraints and ID generation define the mapping, while the relational database stores actual values.

    Why this example? Change the ID strategy and the nullable attribute to see how the example schema changes.

    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

      Metadata bridges objects and rows; schema generation is not a migration tool.

      Try and observe

      Compare assigned IDs and identity generation, then inspect the name constraint.

      3. Persistence unit bootstrap and setup errors

      A resource-local persistence unit configures provider, entity metadata, JDBC URL, credentials and schema policy. The factory is relatively expensive and commonly reused for the application lifetime. An EntityManager is shorter-lived. Connection or dependency problems must be resolved before running persistence operations.

      Why this example? Toggle driver availability and database reachability; inspect the successful or failed startup path.

      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

        Bootstrap connects configuration to runtime objects, not to a generic Java compiler.

        Try and observe

        Try missing driver first, then reachable server with driver present.

        4. Entity lifecycle — managed versus detached

        A newly constructed entity is transient; persist makes a new entity managed, find loads a managed entity, detach or context close ends tracking, and remove marks a managed entity for deletion. Managed modifications can be synchronized automatically. Detached changes require a deliberate merge or another managed update.

        Why this example? Modify the same student with and without detachment, then commit or roll back.

        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

          The entity lifecycle decides whether Java changes become persistent changes.

          Try and observe

          Compare commit while managed with commit after detach; both Java objects have marks 90 but database results differ.

          5. Persistence context identity map

          Within one persistence context, there is at most one managed entity instance for a given persistent identity. This property enables coherent updates and avoids repeated identifier loads. A different EntityManager has a separate identity map; this lab disables L2 cache and assumes a stable database.

          Why this example? Change context and identifier to compare object reference equality and SQL counts.

          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

            Identity reuse is different from database value equality or caching a missing record.

            Try and observe

            Use an existing ID twice in one context, then separate contexts. Try a missing ID to see null.

            6. Schema policy — validation versus disposable generation

            Hibernate can validate a schema or generate it for development. Validation detects mapped schema mismatches without repairing them. A destructive schema action such as create-drop is appropriate only for disposable test databases. Real application schemas should evolve with controlled migrations.

            Why this example? Choose schema policy and existing schema condition; observe startup result and schema action.

            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

              Schema configuration controls database lifecycle and can destroy data if misused.

              Try and observe

              Try validate on a missing schema, then select create-drop only in the virtual test lab.

              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
              @Entity / @IdDeclare a persistent type and its identifier
              Persistence.createEntityManagerFactoryBootstrap a persistence unit
              emf.createEntityManager()Open one persistence context
              em.find(Student.class, id)Lookup by identifier
              em.flush()Synchronize managed changes to SQL within the transaction
              em.close()Close the context; managed entities become detached

              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. Create a reproducible Maven + H2 lab

              Procedure

              1. Create pom.xml at project root. Use a JDK 21 Maven project.
              2. Create src/main/resources/META-INF/persistence.xml using the XML below.
              3. Create src/main/java/demo/Student.java and App.java using the second example.
              4. Run App.main in your IDE after importing Maven dependencies. H2 is in-memory and create-drop is intentionally destructive only in the disposable lab.
              Code / configuration
              <project xmlns="http://maven.apache.org/POM/4.0.0">
                <modelVersion>4.0.0</modelVersion>
                <groupId>in.makeacademy</groupId><artifactId>jpa-lab</artifactId><version>1.0</version>
                <properties><maven.compiler.release>21</maven.compiler.release></properties>
                <dependencies>
                  <dependency><groupId>org.hibernate.orm</groupId><artifactId>hibernate-core</artifactId><version>6.6.18.Final</version></dependency>
                  <dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.3.232</version><scope>runtime</scope></dependency>
                </dependencies>
                <build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version></plugin></plugins></build>
              </project>
              
              <!-- Separate file: src/main/resources/META-INF/persistence.xml -->
              <persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.1">
                <persistence-unit name="school" transaction-type="RESOURCE_LOCAL">
                  <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
                  <class>demo.Student</class>
                  <properties>
                    <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
                    <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:school;DB_CLOSE_DELAY=-1"/>
                    <property name="jakarta.persistence.jdbc.user" value="sa"/>
                    <property name="jakarta.persistence.jdbc.password" value=""/>
                    <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
                    <property name="hibernate.show_sql" value="true"/>
                    <property name="hibernate.format_sql" value="true"/>
                  </properties>
                </persistence-unit>
              </persistence>
              Expected result: The provider creates the student table, inserts the example row and releases resources on close.

              2. Define a student entity and run the first persistence operation

              Procedure

              1. Save Student.java and App.java separately in src/main/java/demo/.
              2. The identifier is assigned by the application, avoiding generated ID timing ambiguity.
              3. Run App.main. Observe INSERT and the printed name; find may use the still-managed instance.
              4. Close and recreate the EntityManager while the factory is open to see a database lookup.
              Code / configuration
              package demo;
              import jakarta.persistence.*;
              @Entity @Table(name="student")
              public class Student {
                  @Id public Long id;
                  @Column(nullable=false) public String name;
                  public int marks;
                  public Student() {}
                  public Student(Long id, String name, int marks) {
                      this.id=id; this.name=name; this.marks=marks;
                  }
              }
              
              // Separate file: App.java
              package demo;
              import jakarta.persistence.*;
              public class App {
                public static void main(String[] args) {
                  try (var emf=Persistence.createEntityManagerFactory("school");
                       var em=emf.createEntityManager()) {
                    var tx=em.getTransaction();
                    try {
                      tx.begin();
                      em.persist(new Student(101L,"Anu",80));
                      tx.commit();
                      System.out.println(em.find(Student.class,101L).name);
                    } catch (RuntimeException ex) {
                      if(tx.isActive()) tx.rollback();
                      throw ex;
                    }
                  }
                }
              }
              Expected result: Anu is printed after the successful commit. Hibernate logs illustrative SQL; the exact SQL depends on mapping.

              Predict the outcome before you run

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

              1. Is Hibernate a replacement for JDBC?

              No. Hibernate typically uses JDBC underneath to execute SQL.

              2. Why should an EntityManager not be shared between threads?

              Its persistence context is mutable and not thread-safe.

              3. Does flush make a write durable?

              No. Commit finalizes a successful database transaction.

              Hands-on practice and assessment

              Programming challenge

              Build the H2 project in the worked example. Change the entity field and inspect the SQL produced by Hibernate; compare a managed object with a detached object.

              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

              JPA is a specification, not a database or driver. Hibernate is an implementation; use jakarta.persistence imports for this baseline. SQL and flush timing depend on the provider, identifier strategy, dialect and configuration. Use create-drop only in disposable lab databases.