Skip to lesson

Validating entities against the schema

A teammate adds an entity field and forgets the migration. Everything compiles, but the first request that touches the field fails with an SQL error, perhaps days later on the live server.

Startup order: Flyway migrates, then Hibernate validates

Schema validation is the check Hibernate runs at startup with ddl-auto=validate: it looks up each entity's table, columns and column types in the real database, and stops the app if one is wrong.

Example 1 is the startup log: Flyway migrates first, and only then does Hibernate validate the result.

Example 1 · Startup log: Flyway first, then Hibernate

Runs in: the shoplite-api Spring Boot project

Text
# src/main/resources/application.yml (the lines that matter here)spring:  flyway:    locations: classpath:db/migration  jpa:    open-in-view: false    hibernate:      ddl-auto: validate            # Hibernate only checks the tables Flyway made; it never changes them
Sample output
$ mvn spring-boot:run        (empty database shoplite_flyway; log prefix trimmed)
INFO org.flywaydb.core.FlywayExecutor : Database: jdbc:mysql://localhost:3306/shoplite_flyway (MySQL 8.4)
INFO o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.100s)
INFO o.f.core.internal.command.DbMigrate : Migrating schema `shoplite_flyway` to version "1 - create schema"
INFO o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `shoplite_flyway`, now at version v1 (execution time 00:01.582s)
INFO org.hibernate.orm.jpa : HHH008540: Processing PersistenceUnitInfo [name: default]
INFO j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
INFO com.shoplite.ShopliteApiApplication : Started ShopliteApiApplication in 35.563 seconds (process running for 37.372)

When Flyway fails, the error says who waits for whom:
Error creating bean with name 'entityManagerFactory' ...: Failed to initialize dependency 'flywayInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory'

What this code does

  • All Flyway lines come before the first Hibernate line (HHH008540): the tables exist before Hibernate looks at them.
  • Hibernate validated quietly: "Initialized JPA EntityManagerFactory" means every entity matched. Validation logs nothing when all is well.
  • The last line is from a failed run in the earlier lessons: Spring could not create Hibernate because its dependency flywayInitializer failed first.

Spring Boot makes the entityManagerFactory bean (Hibernate) depend on the flywayInitializer bean, so Flyway always runs first, and Hibernate checks the schema after the newest migration, which is exactly the schema the code will use. Validation never changes anything.

Without it, a missing column shows up as an SQL error on the first request that touches it, maybe days later in production. With it, the mismatch is a startup failure on your laptop, with the table and column named.

Validation checks only what the entities map. Extra tables, extra columns, indexes, CHECK constraints and defaults are not checked, so a column you forgot to drop never fails validation.

Reading validation errors

Examples 2 to 4 each break the schema in one way and show the error Hibernate prints.

Example 2 · A new entity without its migration: missing table

Runs in: a copy of the shoplite-api project (database shoplite at version 1.1)

GstSlab.javaJava
// src/main/java/com/shoplite/product/GstSlab.java (added, but no migration creates gst_slabs)package com.shoplite.product;
import java.math.BigDecimal;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.Id;import jakarta.persistence.Table;
@Entity@Table(name = "gst_slabs")public class GstSlab {
    @Id    @Column(precision = 4, scale = 2)    private BigDecimal rate;
    @Column(nullable = false, length = 60)    private String description;
    protected GstSlab() {    }}
Sample output
INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite`: 1.1
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite` is up to date. No migration necessary.
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing table [gst_slabs]

What this code does

  • Flyway found nothing to do, because nobody wrote a migration for the new table; then Hibernate looked for gst_slabs and stopped the app.
  • The fix is a migration (V3__create_gst_slabs.sql with the CREATE TABLE and its rows), committed in the same change as the entity.
  • With ddl-auto=update Hibernate would have created the table silently, with its own guessed types, on each developer's machine.

Example 3 · A new field without its column: missing column

Runs in: a copy of the shoplite-api project (database shoplite at version 1.1)

Java
// src/main/java/com/shoplite/product/Product.java (one field added)@Column(nullable = false, precision = 10, scale = 2)private BigDecimal price;
@Column(name = "gst_rate", nullable = false, precision = 4, scale = 2)private BigDecimal gstRate;          // new: no migration adds gst_rate yet
@Column(nullable = false)private int stock;
Sample output
INFO o.f.core.internal.command.DbMigrate : Schema `shoplite` is up to date. No migration necessary.
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing column [gst_rate] in table [products]

What this code does

  • The message names the column and the table, so you know which entity and which migration to look at.
  • Fix: V3__add_gst_rate_to_products.sql with ALTER TABLE products ADD COLUMN gst_rate DECIMAL(4,2) NOT NULL DEFAULT 18.00;, as in the evolving-schema lesson.
  • The reverse order is safe: run the migration first (an extra column is allowed), map the field in a later commit.

Example 4 · Wrong Java types: double for DECIMAL, Long for INT

Runs in: a copy of the shoplite-api project (database shoplite at version 1.1)

Java
// Try 1: Product.price as double (keeping precision and scale)@Column(nullable = false, precision = 10, scale = 2)private double price;
// Try 2: the same field without precision and scale@Column(nullable = false)private double price;
// Try 3: price back to BigDecimal, but a Long id on Product@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "product_id")private Long id;
Sample output
Try 1:
Caused by: java.lang.IllegalArgumentException: scale has no meaning for SQL floating point types

Try 2:
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]

Try 3:
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [product_id] in table [order_items]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]

What this code does

  • A double cannot hold DECIMAL(10,2) exactly, which is why money is BigDecimal. Hibernate 7 even refuses scale on a floating-point field before validation starts.
  • "found" is MySQL's real type, "expecting" is what the Java field needs. Here the fix is in Java: BigDecimal price, Integer id.
  • Try 3 names order_items.product_id, not products: a foreign key column must have its target id's type, so one Long id makes every column that points at it wrong. ShopLite uses Integer ids for its INT columns.

Every validation failure ends in a Caused by: org.hibernate.tool.schema.spi.SchemaManagementException line. Skip the long bean names above it and read that line: it is one of three messages, and each has one usual fix.

  • missing table [gst_slabs]: an entity has no table. Write the migration, or fix @Table(name = ...).
  • missing column [gst_rate] in table [products]: a field has no column. Write the migration that adds it, or fix @Column(name = ...).
  • wrong column type encountered in column [price] ...; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]: the Java type does not match. "found" is the database, "expecting" is what the field would need. Usually change the field (BigDecimal for DECIMAL, Integer for INT).
  • The error names the first problem only. Fix it, restart, and read the next one.

Fix the error

Fix the field type

Read the real validation error, then pick the line that fixes the field.

Round 1 of 2

The price column in MySQL is DECIMAL(10,2).

@Column(nullable = false)
private double price;

Error

Schema validation: wrong column type encountered in column [price] in table [products];
found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]

A fresh-database integration test

A fresh-database test empties a test database, runs every migration, then starts the whole app so validate checks the result. It proves a new machine can be built from the migrations alone.

Example 5 is FreshDatabaseMigrationIT: it cleans shoplite_test, runs every migration and starts the app.

Example 5 · FreshDatabaseMigrationIT: every migration on an empty database

Runs in: the shoplite-api Spring Boot project

Java
// src/test/java/com/shoplite/FreshDatabaseMigrationIT.javapackage com.shoplite;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.List;
import org.flywaydb.core.Flyway;import org.flywaydb.core.api.MigrationInfo;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.test.context.TestConfiguration;import org.springframework.boot.test.web.server.LocalServerPort;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Import;import org.springframework.jdbc.core.simple.JdbcClient;import org.springframework.test.context.ActiveProfiles;
/** * Builds the test database from nothing with every migration, then starts the whole app. * The app only starts if Hibernate's ddl-auto=validate accepts the migrated schema, * so a green run proves the migrations work AND match the entities. */@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)@ActiveProfiles("test")@Import(FreshDatabaseMigrationIT.CleanThenMigrate.class)class FreshDatabaseMigrationIT {
    @TestConfiguration    static class CleanThenMigrate {
        @Bean        FlywayMigrationStrategy cleanThenMigrate() {            return flyway -> {                flyway.clean();                flyway.migrate();     // V1, V1.1 (sample data), V2 ...            };        }    }
    @Autowired    private Flyway flyway;
    @Autowired    private JdbcClient jdbc;
    @LocalServerPort    private int port;
    @Test    void everyMigrationRanAndNoneIsPending() {        List<String> applied = versions(flyway.info().applied());
        assertThat(applied).containsExactly("1", "1.1", "2");        assertThat(flyway.info().pending()).isEmpty();        assertThat(flyway.info().current().getVersion().getVersion()).isEqualTo("2");    }
    @Test    void sampleDataIsLoaded() {        Integer customers = jdbc.sql("SELECT COUNT(*) FROM customers").query(Integer.class).single();        Integer orders = jdbc.sql("SELECT COUNT(*) FROM orders").query(Integer.class).single();
        assertThat(customers).isEqualTo(8);        assertThat(orders).isEqualTo(16);    }
    @Test    void orderHistoryIndexCoversCustomerThenDate() {        List<String> columns = jdbc.sql("""                SELECT column_name FROM information_schema.statistics                WHERE table_schema = DATABASE() AND table_name = 'orders'                  AND index_name = 'idx_orders_customer_ordered_at'                ORDER BY seq_in_index""")                .query(String.class)                .list();
        assertThat(columns).containsExactly("customer_id", "ordered_at");    }
    @Test    void entitiesReadTheMigratedTables() throws Exception {        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/api/v1/products/1")).build();        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        assertThat(response.statusCode()).isEqualTo(200);        assertThat(response.body()).contains("\"sku\":\"MOB-RN13\"", "\"categoryName\":\"Mobiles\"", "\"price\":17999.00");    }
    private static List<String> versions(MigrationInfo[] migrations) {        return java.util.Arrays.stream(migrations).map(m -> m.getVersion().getVersion()).toList();    }}
Sample output
$ mvn verify        (TEST_DB_URL=jdbc:mysql://localhost:3306/shoplite_test; log prefix trimmed)
[INFO] --- failsafe:3.5.6:integration-test (default) @ shoplite-api ---
[INFO] Running com.shoplite.FreshDatabaseMigrationIT
INFO o.f.c.i.command.clean.CleanExecutor: Successfully dropped pre-schema database level objects (execution time 00:00.006s)
INFO o.f.c.i.command.clean.CleanExecutor: Successfully cleaned schema `shoplite_test` (execution time 00:00.778s)
INFO o.f.c.i.command.clean.CleanExecutor: Successfully cleaned schema `shoplite_test` (execution time 00:00.022s)
INFO o.f.c.i.command.clean.CleanExecutor: Successfully dropped post-schema database level objects (execution time 00:00.002s)
INFO o.f.core.internal.command.DbMigrate: Current version of schema `shoplite_test`: << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate: Migrating schema `shoplite_test` to version "1 - create schema"
INFO o.f.core.internal.command.DbMigrate: Migrating schema `shoplite_test` to version "1.1 - sample data"
INFO o.f.core.internal.command.DbMigrate: Migrating schema `shoplite_test` to version "2 - add order history index"
INFO o.f.core.internal.command.DbMigrate: Successfully applied 3 migrations to schema `shoplite_test`, now at version v2 (execution time 00:01.267s)
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 39.89 s -- in com.shoplite.FreshDatabaseMigrationIT
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- failsafe:3.5.6:verify (default) @ shoplite-api ---
[INFO] BUILD SUCCESS

What this code does

  • The CleanThenMigrate bean replaces Spring Boot's plain migrate(): clean empties shoplite_test, then V1, V1.1 and V2 run on an empty database.
  • If any entity did not match, the context would fail and all four tests would error with "Failed to load ApplicationContext". A green run means migrations and entities agree.
  • The tests also check the history (1, 1.1, 2, nothing pending), the sample rows, the new index's columns and a real HTTP read through JPA.

Your dev database has grown over months, with baselines, repairs and hand fixes. A brand new database, such as a new teammate's laptop or a new test server, must be buildable from the migrations alone, and this test proves it on every build.

Spring Boot calls a FlywayMigrationStrategy bean, if there is one, instead of a plain migrate(); the test registers one that calls clean() then migrate(). The test runs as an *IT class in mvn verify, against shoplite_test, never your dev database. A green run proves three things at once: every script runs on an empty MySQL, the scripts run in the right order, and the entities match the final schema.

spring.flyway.clean-disabled

spring.flyway.clean-disabled is the Flyway setting that blocks the clean command. It is true by default, so Flyway refuses to drop a database's objects unless you allow it.

Example 6 shows application-test.yml, the only file that sets clean-disabled to false.

Example 6 · application-test.yml: the only place clean is allowed

Runs in: the shoplite-api Spring Boot project

YAML
# src/test/resources/application-test.yml# Integration tests (*IT) use their own database, never your dev data.# Flyway rebuilds it from nothing before the tests: clean, then every migration plus the sample rows.spring:  datasource:    url: ${TEST_DB_URL:jdbc:mysql://localhost:3306/shoplite_test}    username: ${DB_USER:root}    password: ${DB_PASSWORD}  flyway:    locations: classpath:db/migration,classpath:db/dev-data    clean-disabled: false           # only here: clean wipes the whole database
Sample output
Without the clean-disabled line (the default, true):
[ERROR] Tests run: 4, Failures: 0, Errors: 4, Skipped: 0 <<< FAILURE! -- in com.shoplite.FreshDatabaseMigrationIT
...
Caused by: org.flywaydb.core.api.FlywayException: Unable to execute clean as it has been disabled with the 'flyway.cleanDisabled' property.

With the line: Tests run: 4, Failures: 0, Errors: 0 (Example 5)

What this code does

  • The guard works: with the default setting the strategy's clean() throws before touching any table.
  • The setting lives in src/test/resources, so it is on the classpath only during tests and never inside the jar you deploy.
  • The URL defaults to shoplite_test, a database you create empty once (CREATE DATABASE shoplite_test). Point TEST_DB_URL at a throwaway database only.

clean drops every table, view and procedure in the configured schema, with all its rows, then the history table. That is right for a test database and a disaster anywhere else: one wrong DB_URL and production is empty. ShopLite sets the flag to false only in src/test/resources/application-test.yml, which is not even packaged into the jar. Never put clean-disabled: false in application.yml or a prod profile, and never call clean() from main code.

If you forget the test setting, the test strategy calls clean() and the context fails with "Unable to execute clean as it has been disabled with the 'flyway.cleanDisabled' property". That error is the guard doing its job.

Flyway 10 removed the old cleanOnValidationError option, which cleaned automatically on errors. If you meet it in an old project, delete it.

Next step

Check your understanding

12 quick questions