Generate a database update scripts with Hibernate/Spring

tibo picture tibo · Nov 13, 2013 · Viewed 12.2k times · Source

I have a project where we use to rely on hibernate to update database with changes (hibernate.hbm2ddl.auto=update)... even on prod... I am migrating that to use liquibase instead.

My only concern is that not everyone is a sql guru in my team, so I am looking for a simple way to generate the sql script that hibernate would have done if it was updating the database.

We are all using Intellij IDEA but couldn't find this feature.

Do you know any tool capable of doing that?

Thank you

Answer

darrachequesne picture darrachequesne · Mar 20, 2016

To actually display the scripts generated by Hibernate from your mappings, you can:

  • as suggested by Andrei I, add those two lines to your application.properties:

    spring.jpa.hibernate.ddl-auto=validate
    logging.level.org.hibernate.tool.hbm2ddl=DEBUG
    

Source for Hibernate 4.3: SchemaUpdate.java

  • or manually generate those scripts with the following code:

    LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource);
    sessionFactory.scanPackages("your.package.containing.entities");
    Dialect dialect = new MySQL5Dialect(); // select your dialect
    DatabaseMetadata metadata = new DatabaseMetadata(dataSource.getConnection(), dialect, sessionFactory);
    List<SchemaUpdateScript> scripts = sessionFactory.generateSchemaUpdateScriptList(dialect, metadata);
    
    Formatter formatter = FormatStyle.DDL.getFormatter();
    for (SchemaUpdateScript script : scripts) {
       System.err.println(formatter.format(script.getScript()) + ";");
    }
    

You can even add this code in a @Test, as described here.

Good luck!