views:

210

answers:

2

I just wanted to hear the opinion of Hibernate experts about DB schema generation best practices for Hibernate/JPA based projects. Especially:

  1. What strategy to use when the project has just started? Is it recommended to let Hibernate automatically generate the schema in this phase or is it better to create the database tables manually from earliest phases of the project?

  2. Pretending that throughout the project the schema was being generated using Hibernate, is it better to disable automatic schema generation and manually create the database schema just before the system is released into production?

  3. And after the system has been released into production, what is the best practice for maintaining the entity classes and the DB schema (e.g. adding/renaming/updating columns, renaming tables, etc.)?

Thanks in advance.

+4  A: 
  1. It's always recommended to generate the schema manually, preferably by a tool supporting database schema revisions, such as the great Liquibase. Generating the schema from the entities is great in theory, but were fragile in practice and causes lots of problems in the long run(trust me on this).

  2. In productions it's always best to have manually generated and review the schema.

  3. You make an update the an entity and create a matching update script(revision) to update your database schema to reflect the entity change. You can create a custom solution(I've written a few) or use something more popular like liquibase(it even supports schema changes rollbacks). If you're using a build tool such as maven or ant - it's recommend to plug the db schema update util into the build process so that fresh builds stay in sync with the schema.

Bozhidar Batsov
+1  A: 

Although disputable, I'd say that the answer to all 3 questions is: let hibernate automatically generate the tables in the schema.

I haven't had any problems with that so far. You might need to clean some field up manually from time to time, but this is no headache compared to separately keeping track of DDL scripts - i.e. managing their revisions and synchronizing them with entity changes (and vice-versa)

For deploying on production - an obvious tip - first make sure everything is generated OK on the test environment and then deploy on production.

Bozho
But pretend that you have to change your entity relationships in the production environment in a way that will lead to the creation of new tables, and as a result, some data that used to be a part of an old table has to be inserted into these new tables. For example, pretend that you had an entity named Person that had fields for address information and now you want to create a separate entity for holding the address info. This will lead to creation of a new table and you have to migrate the address data from the person table to this new table. But Hibernate cannot do this automatically...
Bytecode Ninja
no, but it is simple enough to do it manually.
Bozho