I'd like to use the Hibernate/HBM2DDL schema generation as a starting point for managing my application's SQL schema using a tool like Liquibase or Flyway. To assist with that, I need a small utility in my project that I can run that will print out the auto-generated schema.
With older versions or Hibernate, this was relatively simple. Something like the following would work:
EntityManagerFactory emf = null; // TODO: create your EMF the usual way.
Class<? extends Dialect> hibernateDialectType = null; // TODO: e.g. HSQLDialect.class.
Configuration hibernateConfig = new Configuration();
hibernateConfig.setProperty(Environment.DIALECT, hibernateDialectType.getName());
for (EntityType<?> entityType : emf.getMetamodel().getEntities()) {
hibernateConfig.addAnnotatedClass(entityType.getJavaType());
}
SchemaExport schemaExporter = new SchemaExport(hibernateConfig);
schemaExporter.setFormat(true);
schemaExporter.setDelimiter(";");
schemaExporter.create(Target.SCRIPT);
But as of at least Hibernate 5.2, the SchemaExport utility can no be built from a Hibernate Configuration instance.
So how can this be done nowadays?
After digging through the Hibernate Ant task's source on GitHub, I came up with the following solution:
Takes a bit more code these days, but still works, so good enough.