Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/JPA DB Schema Generation Best Practices

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.)?

like image 375
Behrang Avatar asked Apr 06 '10 14:04

Behrang


People also ask

How does JPA define schema?

In the jpa-2.0 feature, which is built on OpenJPA, you can generate data definition langugage (DDL) or interact directly with the database to define table schemas based on the JPA entity definition by using the SchemaMapper tool.

What does Spring JPA generate DDL do?

spring. jpa. generate-ddl (boolean) switches the feature on and off and is vendor independent.


2 Answers

  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 to 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.

like image 113
Bozhidar Batsov Avatar answered Sep 28 '22 21:09

Bozhidar Batsov


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.

like image 27
Bozho Avatar answered Sep 28 '22 21:09

Bozho