javahibernateschemaexport

How do I export schema after upgrading Hibernate to 5.4.1?


I've recently updated Hibernate from 4.3.7 to 5.4.1 and the SchemaExport API has changed since 5.1. This code now shows compilation problems (on SchemaExport constructor and execute method).

/**
 * Method to generate a SQL script which aim is to create SQL tables for the
 * entities indicated as parameters.
 */
private void generateScript(Class<?>... classes) {
    Configuration configuration = new Configuration();
    configuration.setProperty(Environment.DIALECT, entityManagerFactory.getProperties().get(DIALECT_PROPERTY).toString());
    for (Class<?> entityClass : classes) {
        configuration.addAnnotatedClass(entityClass);
    }
    SchemaExport schemaExport = new SchemaExport(configuration);
    schemaExport.setDelimiter(SCRIPT_DELIMITER);
    schemaExport.setOutputFile(getScriptPath());
    schemaExport.setFormat(true);
    boolean consolePrint = false;
    boolean exportInDatabase = false;
    schemaExport.execute(consolePrint, exportInDatabase, false, true);
}

I've seen other questions related to this problem, but nothnig specific enough to help me rewrite this function.


Solution

  • Here is what I've done and it works :

    private void genererScript(Class<?>... classes) {
    
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .applySetting(Environment.DIALECT, entityManagerFactory.getProperties().get(DIALECT_PROPERTY).toString())
                .build();
    
        MetadataSources sources = new MetadataSources( standardRegistry );
        for (Class<?> entityClass : classes) {
            sources.addAnnotatedClass(entityClass);
        }
    
        MetadataImplementor metadata = (MetadataImplementor) sources
                .getMetadataBuilder()
                .build();
    
        EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.SCRIPT);
    
        try {
            Files.delete(Paths.get(getScriptPath()));
        } catch (IOException e) {
            /*
             * The file did not exist...
             * we do nothing.
             */
        }
    
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.setDelimiter(SCRIPT_DELIMITER);
        schemaExport.setOutputFile(getScriptPath());
        schemaExport.setFormat(true);
        schemaExport.createOnly(targetTypes, metadata);
    }