Lukas Eder Lukas Eder - 5 months ago 143
Java Question

Where did Configuration.generateSchemaCreationScript() go in Hibernate 5

In Hibernate 4.x, I used to generate and export the schema as defined in annotated entities as follows (using Spring to find annotated entities on the class path):

Connection connection =
DriverManager.getConnection("jdbc:h2:mem:jooq-meta-extensions", "sa", "");

Configuration configuration = new Configuration()
.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

// [...] adding annotated classes to Configuration here...

configuration.generateSchemaCreationScript(
Dialect.getDialect(configuration.getProperties()));
SchemaExport export = new SchemaExport(configuration, connection);
export.create(true, true);


This no longer works in Hibernate 5.0:



I didn't really find any obvious references to this change in the migration guide apart from:


Quite a few methods have been removed from Configuration


What is the correct way to generate and export a database on an existing JDBC connection with Hibernate 5.0 based on a set of annotated entities? (Pure JPA-based solutions are fine, too)

(note, just removing the call to
generateSchemaCreationScript()
seems to work, but I would prefer to be sure to get this right)

Answer

Thanks to the answers by Vlad and Gunnar, I've managed to find my way through the new configuration API to produce the equivalent export logic with

Hibernate 5:

MetadataSources metadata = new MetadataSources(
    new StandardServiceRegistryBuilder()
        .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
        .build());

// [...] adding annotated classes to metadata here...
metadata.addAnnotatedClass(...);

SchemaExport export = new SchemaExport(
    (MetadataImplementor) metadata.buildMetadata(),
    connection // pre-configured Connection here
);
export.create(true, true);

Hibernate 4:

As a reminder, here's how this worked in Hibernate 4:

Configuration configuration = new Configuration()
    .setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

// [...] adding annotated classes to metadata here...
configuration.addAnnotatedClass(...);

configuration.generateSchemaCreationScript(
    Dialect.getDialect(configuration.getProperties()));
SchemaExport export = new SchemaExport(configuration, connection);
export.create(true, true);
Comments