Search code examples
javahibernatehbm2ddl

ORM - Are DDL scripts required?


Answer says, not to trust hibernate.hbm2ddl.auto setting for production.

My understanding of using ORM:

1) To avoid designing & normalising DB schema at database layer(say RDBMS). In mongoDB world, ODM is used.

2) To avoid embedding SQL query language in code(say java).

3) To just think about storing and retrieving objects(in OOP sense)


Running DDL scripts breaks the purpose of using ORM tool and looks similar to JDBC approach except it provides the SQL dialect for vendor specific database.

For production, Can running of DDL scripts mandatory for safety?


Solution

  • Running DDL scripts manually breaks the purpose of using ORM tool.

    No, it does not.

    An Object-Relational Mapping tool is tool that helps translate data from your tables into objects that you can use in your object-orianted programming language - it has nothing to do with database administration.

    Hibernate can generate a DDL based on what your classes look like right now, but it has no sense of history.

    If all you're doing is adding new columns or tables you'll probably be fine but the minute you rename a column you're out of luck because Hibernate will see the old column and won't find a mapping to it so it will remove it and then create a new column using the new name. If you have a non-null requirement on that column you're screwed because you can't tell Hibernate what the default value is (well, there's a hack but please don't do this.)

    You're also very limited in how you can change the types of columns - if the contents of the column can't be translated automatically by the database you're out of luck.

    As an example we switched our databases from storing UUIDs in binary to storing it as a VARCHAR a while back and we had to manually convert them from binary to hexadecimal notation becasue MySQL can't do that automatically - you'd be properly screwed if you tried to do that with Hibernate's auto-DDL.

    There's also no way of telling Hibernate where to create indexes - you'll get an index on each primary key column but if you want extra indexes you'll have to add these manually.

    The DDL auto-generation of Hibernate is good for validating that your classes map correctly to your tables, but it should never be used to alter your production databases.

    So to answer your question:

    For production, does manual run of DDL scripts mandatory for safety?

    Yes! And I recommend you use a management tool like Liquibase or Flyway to aid with it.