I am currently setting up a Java Spring Boot project and I'm a bit confused about the hibernate.hbm2ddl.auto configuration property. I know it handles the database schema generation, but I want to understand the exact behavior of all possible values like create, update, and validate. What are the best practices for using these in a development environment versus a production environment to ensure I don't accidentally lose any critical data?
3 answers
The hbm2ddl.auto property is a powerful tool for managing your schema. The main values are:
-
validate: Just checks if the schema matches the entities; it makes no changes.
-
update: Updates the existing schema with changes (e.g., adding columns) but won't delete data.
-
create: Drops existing tables and creates new ones every time the SessionFactory is created.
-
create-drop: Similar to create, but also drops the tables when the application shuts down.
-
none: Does nothing. In production, you should almost always use
validateornoneand handle migrations with tools like Liquibase or Flyway to prevent data loss.
Are you finding that the update value occasionally fails to rename columns or handle complex constraint changes correctly in your local MySQL or PostgreSQL environment?
I always recommend using create-drop for unit tests and validate for everything else. It’s the safest way to ensure your code and database are in sync without risking a wipe.
I agree with Barbara. Relying on update in a shared dev database is a recipe for disaster because it often misses dropped constraints, leading to subtle bugs that are hard to track down.
That is exactly what I'm seeing, Steven. When I rename a field in my Java entity, Hibernate's update just adds a new column instead of renaming the old one, leaving me with a mess of redundant data. Does this mean I should manually write SQL ALTER scripts for any change that isn't a simple addition, or is there a specific Hibernate configuration that can detect property renames more intelligently than the default setting?