Skip to lesson

Why ddl-auto=update is unsafe

On day one, adding a field and restarting just works. A month later someone renames phone to mobile, the app starts without a single complaint, and every customer's number is quietly missing.

What ddl-auto=update does and does not do

ddl-auto is the Spring setting that tells Hibernate what to do to the database tables at startup: nothing, check, create or update them. The value update adds what is missing but never renames, drops or moves data.

With ddl-auto=update, Hibernate compares your entities with the tables at startup and sends CREATE TABLE or ALTER TABLE for whatever looks missing. Example 1 shows what it creates for ShopLite's Customer.

Example 1 · Customer.java with ddl-auto=update on an empty database

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

Customer.javaJava
// src/main/resources/application.yml has://   spring.jpa.hibernate.ddl-auto: update//   logging.level.org.hibernate.SQL: DEBUGpackage com.shoplite.lab;
import java.time.LocalDateTime;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
@Entity@Table(name = "customers")public class Customer {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "customer_id")    private Integer id;
    @Column(name = "full_name", nullable = false, length = 100)    private String fullName;
    @Column(nullable = false, unique = true)    private String email;
    @Column(length = 15)    private String phone;
    @Column(name = "created_at", nullable = false)    private LocalDateTime createdAt = LocalDateTime.now();
    protected Customer() {    }
    public Customer(String fullName, String email, String phone) {        this.fullName = fullName;        this.email = email;        this.phone = phone;    }
    @Override    public String toString() {        return "Customer[id=" + id + ", fullName=" + fullName + ", phone=" + phone + "]";    }}
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
DEBUG org.hibernate.SQL : create table customers (customer_id integer not null auto_increment, created_at datetime(6) not null, email varchar(255) not null, full_name varchar(100) not null, phone varchar(15), primary key (customer_id)) engine=InnoDB
DEBUG org.hibernate.SQL : alter table customers drop index UKrfbvkrffamfql7cjmen8v976v
DEBUG org.hibernate.SQL : alter table customers add constraint UKrfbvkrffamfql7cjmen8v976v unique (email)
INFO  DdlLabApplication : Started DdlLabApplication in 16.58 seconds (process running for 18.207)

mysql> SHOW CREATE TABLE customers;
CREATE TABLE `customers` (
  `customer_id` int NOT NULL AUTO_INCREMENT,
  `created_at` datetime(6) NOT NULL,
  `email` varchar(255) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`customer_id`),
  UNIQUE KEY `UKrfbvkrffamfql7cjmen8v976v` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

What this code does

  • On an empty database update writes the whole CREATE TABLE from the annotations. The lab's LabRunner (a CommandLineRunner) then prints every customer as a LAB line; there are none yet.
  • Compare with the Section 12 design: email VARCHAR(255) and the constraint uq_customers_email became a generated name UKrfbv..., created_at has no DEFAULT CURRENT_TIMESTAMP, and it is datetime(6) (with microseconds) instead of DATETIME.
  • After this run, three Section 12 customers (Asha, Ravi and Meena) were inserted with INSERT statements, so the next examples have data to lose.

Example 2 · Changing a column length: MODIFY COLUMN, or a warning

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

Java
// Customer.java, run 1: phone gets longer@Column(length = 20)private String phone;
// Customer.java, run 2: phone gets shorter, while Ravi's number is "+919876543202"@Column(length = 10)private String phone;
Sample output
run 1 (log prefix trimmed)
DEBUG org.hibernate.SQL : alter table customers modify column phone varchar(20)
INFO  DdlLabApplication : Started DdlLabApplication in 18.25 seconds (process running for 20.059)

run 2
DEBUG org.hibernate.SQL : alter table customers modify column phone varchar(10)
WARN  o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "alter table customers modify column phone varchar(10)" via JDBC [Data truncated for column 'phone' at row 2]
INFO  DdlLabApplication : Started DdlLabApplication in 14.511 seconds (process running for 15.9)
LAB Customer[id=1, fullName=Asha Rao, phone=9876543201]
LAB Customer[id=2, fullName=Ravi Kumar, phone=+919876543202]
LAB Customer[id=3, fullName=Meena Iyer, phone=null]

What this code does

  • Hibernate 7's update changes a column's type when the annotation changes: run 1 widens phone with MODIFY COLUMN.
  • In run 2 MySQL refuses to cut Ravi's 13-character number, but Hibernate only logs a WARN and the app starts. The entity says 10, this database says 20.
  • A database where every number happened to fit would now have varchar(10). Same code, two different schemas: this is what "different results per environment" means.

DDL (Data Definition Language) is the SQL that changes the structure of tables, not their rows. Hibernate's guess is not your design: the email becomes VARCHAR(255) with a random unique-key name, created_at loses its DEFAULT CURRENT_TIMESTAMP, and the Section 12 CHECK constraints never appear.

Hibernate never drops a column or table, never renames anything and never copies data. When a change fails, Hibernate 7 logs a warning and starts anyway (Example 2), so a laptop, the test server and production can each end up with a different schema.

Hibernate 7 also changes column types with ALTER TABLE ... MODIFY COLUMN when a length or type no longer matches. On a big table that rewrites every row while the app starts.

Renaming a field: a new empty column appears

Schema drift is when the databases of one app, such as a laptop and production, end up with different tables or columns. ddl-auto=update causes it, because each database is patched only for what its own startup found.

Example 3 renames the phone field to mobile. Hibernate cannot tell a rename from one field removed and another added, so it adds a new column and leaves the old one behind.

Example 3 · Renaming phone to mobile: the numbers stay behind

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

Java
// Customer.java: only the field name changed@Column(length = 15)private String mobile;                // was: phone
@Overridepublic String toString() {    return "Customer[id=" + id + ", fullName=" + fullName + ", mobile=" + mobile + "]";}
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
DEBUG org.hibernate.SQL : alter table customers add column mobile varchar(15)
INFO  DdlLabApplication : Started DdlLabApplication in 18.153 seconds (process running for 20.063)
DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.mobile from customers c1_0
LAB Customer[id=1, fullName=Asha Rao, mobile=null]
LAB Customer[id=2, fullName=Ravi Kumar, mobile=null]
LAB Customer[id=3, fullName=Meena Iyer, mobile=null]

mysql> SELECT customer_id, full_name, phone, mobile FROM customers;
+-------------+------------+------------+--------+
| customer_id | full_name  | phone      | mobile |
+-------------+------------+------------+--------+
|           1 | Asha Rao   | 9876543201 | NULL   |
|           2 | Ravi Kumar | 9876543202 | NULL   |
|           3 | Meena Iyer | NULL       | NULL   |
+-------------+------------+------------+--------+

What this code does

  • Hibernate sees a field mobile with no column, so it adds one. It has no idea that phone was the same thing under an old name.
  • The app now reads mobile, which is NULL for everyone: to the app, every customer has lost their number. The data is still in phone, a column nothing uses any more.
  • No error, no warning. The bug shows up only as missing SMS messages, possibly weeks later.

Example 4 · Renaming a required field: new customers are rejected

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

Java
// Customer.java: fullName renamed to name (still required)@Column(nullable = false, length = 100)private String name;                  // was: fullName
// LabRunner.java, run with --lab.add=truecustomers.save(new Customer("Sneha Patil", "sneha.patil@example.com", "9876543209"));
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments=--lab.add=true        (log prefix trimmed)
DEBUG org.hibernate.SQL : alter table customers add column name varchar(100) not null
INFO  DdlLabApplication : Started DdlLabApplication in 14.15 seconds (process running for 15.704)
DEBUG org.hibernate.SQL : insert into customers (created_at,email,name,phone) values (?,?,?,?)
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1364, SQLState: HY000
WARN  org.hibernate.orm.jdbc.error : Field 'full_name' doesn't have a default value
ERROR o.s.boot.SpringApplication : Application run failed
org.springframework.dao.DataIntegrityViolationException: could not execute statement [Field 'full_name' doesn't have a default value] [insert into customers (created_at,email,name,phone) values (?,?,?,?)]; SQL [insert into customers (created_at,email,name,phone) values (?,?,?,?)]; constraint [full_name]

mysql> SELECT customer_id, full_name, name, phone FROM customers;
+-------------+------------+------+------------+
| customer_id | full_name  | name | phone      |
+-------------+------------+------+------------+
|           1 | Asha Rao   |      | 9876543201 |
|           2 | Ravi Kumar |      | 9876543202 |
|           3 | Meena Iyer |      | NULL       |
+-------------+------------+------+------------+

What this code does

  • The new name column is NOT NULL, so MySQL gives the existing rows an empty string: every customer's name now reads as blank in the app.
  • The old full_name column is still NOT NULL with no default. Hibernate's INSERT does not mention it, so MySQL rejects every new customer with error 1364.
  • On a live site this is a broken sign-up page right after a deploy, and the fix is manual SQL under pressure.

Every customer's number stays in phone, which the app no longer reads, and mobile is empty. Nothing fails, so nobody notices until a customer says the delivery SMS never came.

Example 4 renames a required field. The new column is NOT NULL, so MySQL fills existing rows with an empty string, and the old full_name column, still NOT NULL with no default, now rejects every new customer.

Predict the output

What does update do to the tables?

Read the entity change, then pick what Hibernate does to the customers table at startup.

Round 1 of 2

The field phone is renamed to mobile. What does the table hold after the restart?

@Entity
public class Customer {
private String fullName;
private String mobile; // was: phone
}

create, create-drop, validate and none

validate is a ddl-auto value that only checks that the tables and columns match the entities, and stops the app if they do not. It never changes the database.

The five ddl-auto values are create, create-drop, update, validate and none. Example 5 shows validate stopping the app at startup.

Example 5 · application.yml: validate stops the app at startup

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

Text
# src/main/resources/application.ymlspring:  jpa:    hibernate:      ddl-auto: validate          # check the tables, never change them# Customer.java still has the renamed field from Example 3:#   @Column(length = 15)#   private String mobile;
Sample output
$ mvn spring-boot:run        (log prefix trimmed)
ERROR j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Unable to build Hibernate SessionFactory  [persistence unit: default] ; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing column [mobile] in table [customers]
ERROR o.s.boot.SpringApplication : Application run failed
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing column [mobile] in table [customers]

What this code does

  • Same rename, but with validate: Hibernate compares and refuses to start, naming the exact column and table.
  • Nothing in the database changed. The fix is a deliberate migration that renames the column (Example 6), reviewed and run the same way everywhere.
  • A failed start on your laptop costs a minute; a silent wrong schema in production costs data.

create drops and recreates every mapped table at startup; create-drop does the same and drops them again at shutdown; none does nothing. create and create-drop delete all rows, so they belong only to throwaway databases. Spring Boot uses create-drop by default only for embedded databases such as H2; for MySQL the default is none.

ShopLite uses validate in every profile, so a mismatch stops the app on your laptop, not on the live server:

  • Laptop, CI, test server and production: validate
  • A throwaway experiment or a test database rebuilt on every run: create-drop
  • update: nowhere that holds data you care about

Migrations: versioned SQL reviewed in Git

A migration is a small SQL script that moves the database schema from one version to the next. Migrations are numbered, run in order, run once per database and are kept in Git.

Example 6 writes the rename from the last section as a migration, V2__rename_phone_to_mobile.sql.

Example 6 · The rename as a migration script

Runs in: the ddl-lab practice project (Spring Boot 4.1, Spring Data JPA, MySQL database shoplite_lab)

SQL
-- src/main/resources/db/migration/V2__rename_phone_to_mobile.sql-- One statement: the column gets its new name and keeps every value.ALTER TABLE customers RENAME COLUMN phone TO mobile;
Sample output
mysql> SELECT customer_id, full_name, mobile FROM customers;
+-------------+------------+------------+
| customer_id | full_name  | mobile     |
+-------------+------------+------------+
|           1 | Asha Rao   | 9876543201 |
|           2 | Ravi Kumar | 9876543202 |
|           3 | Meena Iyer | NULL       |
+-------------+------------+------------+

$ git log --oneline -- src/main/resources/db/migration
4c1e9a2 Rename customers.phone to mobile (V2)
9b07d31 Create the ShopLite schema (V1)

What this code does

  • RENAME COLUMN (MySQL 8.0 and later) keeps the data in place, which update can never do. With the entity field also called mobile, validate passes.
  • The file name carries the version (V2) and a description. A migration tool runs it once per database and remembers that it did; Flyway does that from the next lesson on.
  • The script sits in Git, so the change is reviewed in a pull request and its history is visible. Your commit ids will differ. The Evolving lesson shows how to rename without downtime while old app versions still run.

You write exactly the SQL you mean: one ALTER TABLE ... RENAME COLUMN keeps every value. A teammate reviews the script in the pull request like any other code, and every database, from your laptop to production, runs the same script and ends up in the same shape.

A tool records which scripts each database has already run. The next lesson adds Flyway, the migration tool Spring Boot supports out of the box.

Next step

Check your understanding

11 quick questions