Reputation: 783
I have a spring boot application that is connecting to PostgreSQL database. The DAO layer is implemented using Hibernate
and JPA
and auto-ddl
is enabled so that hibernate takes care of creating table
Suddenly today my friend asked me to alter one of the column type BigInteger
to String
, then I said which is impossible because that column already filled with data and hibernate will not allow that
Now he is telling it is drawback in hibernate and we also had debate on does companies alter column definition based on requirement in production?
Question
Upvotes: 2
Views: 1975
Reputation: 22605
You should never use auto-ddl
in production. It was never intended to be used in production, but for development. The reason why you shouldn't use it is that it might create un-optimal DDL or just damage your data.
The preferred approach to do changes in DB is to create a folder, which would contain all SQL scripts that alter the database structure and store it in version control. The common name is migrations
. Then you could either manually run these scripts on your database or use tool like flyway (my recommendation) or liquibase.
So how can you make use of auto-ddl
? For example, you could create a table for your new entity, then take DDL which was used to create it and after applying some adjustments (if necessary) store it in migrations. You can also use validate from hibernate.hbm2ddl.auto to check if your database matches with your entities.
And finally answering your questions:
auto-ddl
was never intended to do database migrations.auto-ddl
. Someone (DBA or developer) prepares migrations script and then it's applied either manually or by migration tool on release.Upvotes: 9
Reputation: 7267
This is not a drawback of Hibernate, auto-ddl
is designed to create the schema from the model and not update it. The reason is because, as you've found yourself, this is rarely straightforward and may require some "massaging" of the data.
I wouldn't say it's a common practise to change data types in production systems, but it's certainly a valid scenario to find oneself in. In my years I've had to do this a handful of times, although it's usually something as trivial as increasing the size of a varchar
or changing from date
to a datetime
. Changing from a BigInteger
to a String
seems a little unusual and I would question how you've got to that position, it may indicate a problem with the design.
Either way, the solution is to change the data type in the database, which shouldn't be a problem, and then change the Hibernate
mapping to reflect this change.
Upvotes: 2