Java.Hibernate.Middle.What’s the purpose of the hibernate.hbm2ddl.auto property?

Short Answer

The hibernate.hbm2ddl.auto property controls automatic schema generation and management by Hibernate.
It tells Hibernate whether it should create, update, validate, or do nothing with your database schema when your application starts.

🔎 Detailed Explanation

🔹 Common values:
none
Hibernate does nothing with your schema → it won’t touch the database tables.

validate
Hibernate validates your entity mappings against the existing schema → ensures tables/columns match the mappings, but makes no changes.
❌ Throws an error if mismatches are found.

update
Hibernate automatically updates the schema → adds new tables or columns as needed to match your entity mappings.
✅ Good for development.
❌ Risky in production → can cause accidental data loss or schema drift.

create
Hibernate drops the existing schema and creates a new one every time the session factory starts → all data is lost.
✅ Useful for tests or prototyping only.

create-drop
Like create, but Hibernate drops the schema when the session factory closes (e.g., when the app shuts down) → ensures a fresh start every time.

create-only (in newer Hibernate versions)
Creates the schema but doesn’t drop it at shutdown.

🔹 Example configuration
In application.properties or hibernate.cfg.xml:

hibernate.hbm2ddl.auto=update

🔹 When to use each value

ValueUse Case
noneProduction → manage schema manually
validateProduction → ensure schema matches mappings
updateDev/POC → evolve schema automatically
createDev/testing → start with fresh schema
create-dropDev/integration tests → temporary schema

🔹 Important caution
✅ Never use update, create, or create-drop in production → can lead to data loss or unexpected schema changes.
✅ Use database migrations tools (Flyway, Liquibase) for production schema evolution instead.

📌 Key Takeaways

hibernate.hbm2ddl.auto automates schema validation and generation.
✅ Choose carefully → especially between validate, update, and create.
✅ Use update/create/create-drop only for development, not production.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.