Entity-to-Table Mapping

About

  • In JPA, an Entity (@Entity annotated class) represents a table conceptually.

  • However, just creating a Java entity class does not by itself create a table in the database unless certain conditions are met.

It depends on:

  • How our JPA Provider (Hibernate, EclipseLink, etc.) is configured.

  • What DDL (Data Definition Language) generation settings we have.

  • Whether the database already has tables manually created or not.

Step
Behavior

We create an Entity class

It defines how a row of a table should look like (the mapping)

JPA provider (Hibernate) sees your Entity

It can generate a table based on your entity if configured

Otherwise

JPA just expects the table already exists in the database

Behind the Scenes in Spring Data JPA

When our Spring Boot application starts:

  1. Spring Boot Auto-configures Hibernate as the default JPA provider.

  2. Hibernate scans all @Entity classes.

  3. Based on Hibernate settings, it decides whether to:

    • Validate against existing tables (check structure).

    • Create tables from scratch.

    • Update existing tables (alter, add missing columns).

    • Do nothing and assume tables are already correctly created.

The Key Setting: spring.jpa.hibernate.ddl-auto

This property controls whether Hibernate will create/update/validate the schema.

Value
What Happens

none

Do nothing — Hibernate does not touch database schema.

validate

Validate the schema — check if tables/columns match the Entities. Throws error if mismatch.

update

Update the schema — create new tables or columns as necessary.

create

Drop all existing tables and create new ones from Entity mappings on every application start.

create-drop

Same as create, but drops tables when the app stops. Useful for testing.

Example application.yml file

spring:
  jpa:
    hibernate:
      ddl-auto: update

Result: Hibernate will create missing tables and columns if needed.

What If You Don't Set ddl-auto?

  • Spring Boot will by default use create-drop for an in-memory database like H2.

  • For production databases (like MySQL, Postgres), we must set it manually or it might assume none or throw warnings.

Last updated

Was this helpful?