Sub topic 7
Using Flyway together with Hibernate
This chapter assumes you have a Spring Boot project with Spring Data JPA, Flyway on the classpath, and the app_user migrations from the earlier chapters (V1 creates the table, V2 adds display_name). It also assumes you can read a basic JPA entity.
Flyway and Hibernate both know how to create tables. If you let both do it, they will disagree with each other. This chapter explains how to give each tool one job and what to do when they still disagree.
Two tools, two jobs
Hibernate is an object-relational mapper (ORM). It translates between Java objects (entities) and table rows. It can also generate DDL, which is the SQL that creates and changes tables, from your entity classes. Flyway applies SQL files in a fixed order and records what it applied.
The setup that works in production gives these roles:
- Flyway owns the schema. Every table, column, index, and constraint comes from a migration file that is in version control.
- Hibernate owns the mapping. It reads and writes rows through the tables Flyway created. It never changes them.
Hibernate's property ddl-auto (set in Spring Boot as spring.jpa.hibernate.ddl-auto) decides how much schema work Hibernate does at startup.
| Value | What Hibernate does at startup | Use with Flyway? |
|---|---|---|
| `none` | Nothing. | Yes. |
| `validate` | Compares entities to the existing tables and fails startup on a mismatch. It changes nothing. | Yes, recommended. |
| `update` | Adds missing tables and columns, but never drops or renames. | No. |
| `create` | Drops and recreates the schema. | No. |
| `create-drop` | Like `create`, and drops the schema when the application stops. | No. |
If you don't set the property, Spring Boot picks a default. For an embedded database such as H2 it is create-drop. For any other database it is none. The embedded default is a trap, and the testing section below covers it.
The recommended configuration
spring:
flyway:
enabled: true
locations: classpath:db/migration
validate-on-migrate: true
jpa:
hibernate:
ddl-auto: validate
open-in-view: falseddl-auto: validate is what turns Hibernate into a safety check. If a developer renames a field in an entity and forgets the migration, the application refuses to start. You find out on your machine, not in production.
open-in-view is unrelated to schema management. It appears here only because it is a common companion setting that turns off a Spring Boot default. Leave it out if you don't want to change it.
Startup order
Hibernate validates the schema when it builds its EntityManagerFactory. If that happened before Flyway ran, validation would fail on a fresh database, because no tables would exist yet. Spring Boot prevents this by making the EntityManagerFactory bean depend on the Flyway bean. Flyway therefore finishes all pending migrations first.
Spring Boot sets up this dependency for you. You normally don't write any code for it. If you define your own EntityManagerFactory or your own Flyway bean, the automatic ordering may no longer apply. In that case you have to declare the dependency yourself.
A worked example
This entity maps the app_user table from the earlier migrations.
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
@Entity
@Table(name = "app_user")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 100)
private String username;
@Column(name = "display_name", length = 200)
private String displayName;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
protected AppUser() {
}
public AppUser(String username) {
this.username = username;
this.createdAt = LocalDateTime.now();
}
public Long getId() { return id; }
public String getUsername() { return username; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) { this.displayName = displayName; }
public LocalDateTime getCreatedAt() { return createdAt; }
}Each choice here matches a decision in the migrations:
GenerationType.IDENTITYmatchesBIGINT GENERATED ALWAYS AS IDENTITYin V1. The database generates the key, and Hibernate reads it back after the insert. If you usedGenerationType.SEQUENCEinstead, Hibernate would expect a sequence that V1 never created.display_nameis mapped with@Column(name = "display_name"). Spring Boot's default naming strategy already turnsdisplayNameintodisplay_name, but writing the name out makes the link to the migration easy to see.LocalDateTimemaps toTIMESTAMPwithout a time zone, which matchescreated_at TIMESTAMP. UsingInstantorOffsetDateTimecould make Hibernate 6 expectTIMESTAMP WITH TIME ZONE, and validation would then fail.
What validation checks and what it skips
validate checks that:
- every mapped table exists,
- every mapped column exists,
- each column's type is compatible with the Java type.
It does not check:
- column length or precision. A
VARCHAR(50)column passes againstlength = 100. - nullability, unique constraints, foreign keys, or indexes.
- extra tables or columns in the database that no entity maps.
So a passing validate means the entities can talk to the database. It does not mean the schema matches the entities exactly. Constraints and indexes need review in the migration itself.
Common errors
Missing table. The message looks like Schema-validation: missing table [app_user]. The usual causes are:
- Flyway did not run (
spring.flyway.enabled=false). - Flyway used another schema than Hibernate. Check
spring.flyway.schemasandspring.jpa.properties.hibernate.default_schema. - The migration files are not in the configured
locations.
Wrong column type. The message looks like found [int4 (Types#INTEGER)], but expecting [bigint (Types#BIGINT)]. Either the entity uses Long and the migration used INTEGER, or the other way around. Fix it with a new migration if the old one has already been applied, as in this example. Never edit V1.
-- src/main/resources/db/migration/V4__widen_login_count.sql
ALTER TABLE app_user ADD COLUMN login_count INTEGER NOT NULL DEFAULT 0;Suppose V4 has been applied and the entity declares private Long loginCount;. Hibernate expects bigint and finds integer. The corrective migration is the next version:
-- src/main/resources/db/migration/V5__login_count_to_bigint.sql
ALTER TABLE app_user ALTER COLUMN login_count TYPE BIGINT;The ALTER COLUMN ... TYPE syntax is PostgreSQL. Other databases use a different form, such as MODIFY COLUMN in MySQL.
Missing column. You added a field to the entity and did not write the migration. Write the migration. Don't switch to ddl-auto: update to make the error go away. update hides the missing migration, and then the next environment fails because Flyway never recorded the change.
Both tools active. If ddl-auto is update or create while Flyway also runs, Hibernate may create objects Flyway does not know about. Later, a Flyway migration that creates the same object fails with "already exists". Or create-drop removes tables that Flyway recorded as applied, and the history table then lies about the database.
Testing with a real database
Slice tests such as @DataJpaTest replace your configured DataSource with an embedded H2 database by default. Two problems follow:
- Your migrations run on H2, not on your real database engine. SQL that is valid on PostgreSQL may fail or behave differently on H2.
- If
ddl-autois unset, the embedded defaultcreate-dropapplies, and Hibernate rebuilds the schema from the entities. The test then passes without proving that your migrations match your entities.
Turn off the replacement and point the test at a real database, for example one started with Testcontainers or a local test instance.
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.TestPropertySource;
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(properties = "spring.jpa.hibernate.ddl-auto=validate")
class SchemaMatchesEntitiesTest {
@Test
void entitiesMatchMigratedSchema() {
// The context starts only if Flyway's migrations satisfy Hibernate's validation.
}
}The test body is empty on purpose. If startup fails, the test fails, and the error message names the mismatched table or column. @DataJpaTest includes Flyway auto-configuration, so the migrations run before validation.
Using Hibernate to draft DDL
Hibernate can write the DDL it would generate to a file without touching the database. This is a handy way to get a first draft of a CREATE TABLE for a new entity.
spring:
jpa:
properties:
jakarta.persistence.schema-generation.scripts.action: create
jakarta.persistence.schema-generation.scripts.create-target: target/create.sqlTreat the output as a draft. Review it, adjust types and constraints for your database, and then save it as a new versioned migration. Remove the properties again afterwards so normal runs do not write the file.
A checklist for a schema change
- Change the entity.
- Write the next versioned migration that makes the database match.
- Start the application or run the schema test. Flyway applies the migration and Hibernate validates it.
- Commit the entity and the migration file together.
Because validation runs on every startup, a change that forgets step 2 fails at step 3, and not in production.
Exercise
You add private String phone; to the AppUser entity but forget to write a migration. ddl-auto is validate. What happens when the application starts, and how do you fix it without touching any existing migration?
Show answer
Flyway finds nothing pending and does nothing. Hibernate then validates the entity against the table and fails startup with a schema-validation error saying the column phone is missing in table app_user. Fix it by adding a new migration with the next version number, for example V6__add_phone.sql containing ALTER TABLE app_user ADD COLUMN phone VARCHAR(30);. Do not edit an applied migration, and do not switch to ddl-auto: update.
Exercise
A @DataJpaTest passes on your laptop but the same migrations fail on PostgreSQL in CI. Give two reasons the test could have passed, and one setting that closes the gap.
Show answer
The slice test replaced the configured DataSource with an embedded H2 database by default, so the migrations ran on H2 and not on PostgreSQL. If ddl-auto was unset, the embedded default create-drop also let Hibernate build the schema from the entities, so the test never depended on the migrations being correct. Adding @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE), with a real PostgreSQL test database and ddl-auto=validate, closes the gap.