开发者

Use hbm2ddl to generate SQL DDL for database schema update (without losing data)

开发者 https://www.devze.com 2023-01-04 10:56 出处:网络
I have been using hbm2ddl and hbm2java to build my database and POJOs for my project based on my XML mapping files (hbm.xml). I\'m starting to get some real data now in the system, so re-running my an

I have been using hbm2ddl and hbm2java to build my database and POJOs for my project based on my XML mapping files (hbm.xml). I'm starting to get some real data now in the system, so re-running my ant script which drops the database and recreates everything is no longer a viable option since I want to keep the data. I have heard that there is a hbm2ddl.auto feature which can b开发者_JAVA技巧e used to modify the db structure without getting rid of the data, but I gather from some of the answers on s/o that it's not a best practice.

My understanding is that you should write the SQL DDL based on the changes in the mapping file and run it against the DB. I was wondering if hbm2ddl can be used to generate this DDL based on the mapping file. I have also head about LiquiBase, but not sure if those would be appropriate for my situation as I am hoping to keep using the hbm.xml files as the key data definition source.

Comments and suggestions are appreciated - thanks in advance!


It might not be the best way to do this in production environment, but if you are not "live with thousands of users", here's how to do it:

  • set hibernate.hbm2dll to update (this is a hibernate property, set it in hibernate.cfg.xml, or in the spring config, if you use it)
  • every time you (re)start your application, the database schema will be updated with the new fields and constraints.
  • old fields may not be removed, so you can go and clean them up manually
  • primitives, corresponding to columns with not null should be assigned a default or you should go and make a manual UPDATE query. Otherwise you'll get runtime exceptions.


I was asking me the same question last week and I decided to use LiquiBase. There are many statements here on "Stack Overflow" which discourage you from using hbm2ddl in production environments. So do I.

I was running into hbm2ddl's capability limitations when I tried to add unique constraints and I realized that it was time to choose a more sophisticated approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消