Video in progress

How do you rename a column with zero downtime in a table used by a Hibernate entity?

You can't rename it in one go, because during a deploy the old and new versions run together. Expand-contract: add the new column, write to both, migrate the data, switch reads to the new one, and drop the old column only in the last release. Flyway manages the schema and Hibernate only does validate.

📖 Answer

No ddl-auto=update on prod: it can't rename a column, it only adds the new one and leaves the old one. I use spring.jpa.hibernate.ddl-auto=validate and Flyway/Liquibase.

The example is customer.phone → customer.phone_number, with every step a separate release:

  1. Expand. Migration: alter table customer add column phone_number varchar(32); The code still uses the old column. A rolling deploy is safe, because the old version doesn't know about the new column.

  2. Write to both. Temporarily in the entity:

@Column(name = "phone") String phone;
@Column(name = "phone_number") String phoneNumber;

@PrePersist @PreUpdate
void syncPhone() { this.phoneNumber = this.phone; }

Or a trigger in the database. At this stage the old column is still the primary one.

  1. Backfill. update customer set phone_number = phone where phone_number is null: on a big table, in batches, without holding locks for long.

  2. Switch reads to the new column. The code reads from phone_number and still writes to both (there may still be pods running the old version).

  3. Contract. Once every pod is on the new version, the old field is removed from the entity, and in the next release you drop column phone.

What I'm careful about: validate treats a column that's in the entity but missing in the database as an error, so the migration has to run before the code. Native queries and other services may also use the old name, and you have to find them with grep. I add the NOT NULL constraint only after the backfill is done, and on PostgreSQL first as check ... not valid and then validate constraint.