Example usage for org.hibernate.tool.hbm2ddl SchemaExport setFormat

List of usage examples for org.hibernate.tool.hbm2ddl SchemaExport setFormat

Introduction

In this page you can find the example usage for org.hibernate.tool.hbm2ddl SchemaExport setFormat.

Prototype

public SchemaExport setFormat(boolean format) 

Source Link

Document

Should we format the sql strings?

Usage

From source file:com.premiumminds.persistence.utils.HibernateEnversDDL.java

License:Open Source License

private static void createCommand(String[] args) {
    String unitName;//from   www. j  av  a 2  s  .  com
    String filename = null;
    if (args.length < 2)
        System.out.println("Expected unitName");
    else {
        unitName = args[1];
        if (args.length > 2)
            filename = args[2];

        EnversSchemaGenerator esg = new EnversSchemaGenerator(HibernateDDL.getConfiguration(unitName));
        org.hibernate.tool.hbm2ddl.SchemaExport se = esg.export();
        se.setOutputFile(filename);
        se.setFormat(true);
        se.setDelimiter(";");
        se.execute(false, false, false, true);
    }
}

From source file:com.premiumminds.persistence.utils.HibernateEnversDDL.java

License:Open Source License

private static void createDropCommand(String[] args) {
    String unitName;/* w  ww  .  ja v  a2s. c  om*/
    String filename = null;
    if (args.length < 2)
        System.out.println("Expected unitName");
    else {
        unitName = args[1];
        if (args.length > 2)
            filename = args[2];

        EnversSchemaGenerator esg = new EnversSchemaGenerator(HibernateDDL.getConfiguration(unitName));
        org.hibernate.tool.hbm2ddl.SchemaExport se = esg.export();
        se.setOutputFile(filename);
        se.setFormat(true);
        se.setDelimiter(";");
        se.execute(false, false, true, true);
    }
}

From source file:com.siemens.scr.avt.ad.util.HibernateUtil.java

License:Open Source License

public static void main(String[] args) {
    Configuration cfg = new Configuration().configure();
    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setDelimiter(";");
    schemaExport.setFormat(true);
    schemaExport.setOutputFile("createSchema.sql");
    schemaExport.create(true, false);/*w w w  . j  a va 2 s.  co  m*/
}

From source file:com.socialsite.scripts.SchemaCreator.java

License:Open Source License

public static void create() {
    final Configuration cfg = new Configuration().configure();
    final SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setDelimiter(";");
    schemaExport.setFormat(true);
    final File f = new File("src/main/scripts");
    f.mkdirs();/*from w  w w .  ja  va2 s .c o m*/
    schemaExport.setOutputFile("src/main/scripts/schema.sql");
    schemaExport.drop(true, true);
    schemaExport.create(true, true);
}

From source file:com.userweave.config.MPSchemaExport.java

License:Open Source License

/**
 * @param args/*from w  w  w . j  a v a  2  s.co  m*/
 */
public static void main(String[] args) {

    //      if (args.length != 1) {
    //         System.out.println("please specify output filename");
    //      }
    //      
    String filename = "schema.ddl";//args[0];

    final AnnotationConfiguration configuration = new AnnotationConfiguration();

    final Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    configuration.setProperties(properties);

    SchemaExport export = new SchemaExport(configuration);
    export.setDelimiter(";");
    export.setFormat(true);

    File outputFile = new File(filename);
    export.setOutputFile(outputFile.toString());
    export.execute(false, false, false, true);
}

From source file:com.vecna.maven.hibernate.HibernateSchemaExportMojo.java

License:Apache License

/**
 * Exports the schema.//w w w .  j  ava  2  s  .co  m
 * {@inheritDoc}
 */
@Override
protected void executeWithMappings(Configuration configuration)
        throws MojoExecutionException, MojoFailureException {
    SchemaExport schemaExport = new SchemaExport(configuration);
    schemaExport.setFormat(format);

    if (outputFile != null) {
        initializePath();
        schemaExport.setOutputFile(outputFile);
        schemaExport.setDelimiter(delimiter);
    }

    schemaExport.execute(print, export, false, !drop);
}

From source file:com.wavemaker.tools.data.ExportDB.java

License:Open Source License

@Override
protected void customRun() {

    init();/* w  ww . j a v  a2 s . c  om*/

    final Configuration cfg = new Configuration();

    // cfg.addDirectory(this.hbmFilesDir);

    this.hbmFilesDir.find().files().performOperation(new ResourceOperation<com.wavemaker.tools.io.File>() {

        @Override
        public void perform(com.wavemaker.tools.io.File file) {
            if (file.getName().endsWith(".hbm.xml")) {
                cfg.addInputStream(file.getContent().asInputStream());
            }
        }
    });

    Properties connectionProperties = getHibernateConnectionProperties();

    cfg.addProperties(connectionProperties);

    SchemaExport export = null;
    SchemaUpdate update = null;
    File ddlFile = null;

    try {
        if (this.overrideTable) {
            Callable<SchemaExport> t = new Callable<SchemaExport>() {

                @Override
                public SchemaExport call() {
                    return new SchemaExport(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    export = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                export = ResourceClassLoaderUtils.runInClassLoaderContext(true, t, this.classesDir);
            }

            ddlFile = File.createTempFile("ddl", ".sql");
            ddlFile.deleteOnExit();

            export.setOutputFile(ddlFile.getAbsolutePath());
            export.setDelimiter(";");
            export.setFormat(true);

            String extraddl = prepareForExport(this.exportToDatabase);

            export.create(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(export.getExceptions());
            this.errors = filterError(this.errors, connectionProperties);

            this.ddl = IOUtils.read(ddlFile);

            if (!ObjectUtils.isNullOrEmpty(extraddl)) {
                this.ddl = extraddl + "\n" + this.ddl;
            }
        } else {
            Callable<SchemaUpdate> t = new Callable<SchemaUpdate>() {

                @Override
                public SchemaUpdate call() {
                    return new SchemaUpdate(cfg);
                }
            };

            if (this.classesDir == null) {
                try {
                    update = t.call();
                } catch (Exception e) {
                    ReflectionUtils.rethrowRuntimeException(e);
                }
            } else {
                update = ResourceClassLoaderUtils.runInClassLoaderContext(t, this.classesDir);
            }

            prepareForExport(this.exportToDatabase);

            Connection conn = JDBCUtils.getConnection(this.connectionUrl.toString(), this.username,
                    this.password, this.driverClassName);

            Dialect dialect = Dialect.getDialect(connectionProperties);

            DatabaseMetadata meta = new DatabaseMetadata(conn, dialect);

            String[] updateSQL = cfg.generateSchemaUpdateScript(dialect, meta);

            update.execute(this.verbose, this.exportToDatabase);

            this.errors = CastUtils.cast(update.getExceptions());
            StringBuilder sb = new StringBuilder();
            for (String line : updateSQL) {
                sb = sb.append(line);
                sb = sb.append("\n");
            }
            this.ddl = sb.toString();

        }
    } catch (IOException ex) {
        throw new DataServiceRuntimeException(ex);
    } catch (SQLException qex) {
        throw new DataServiceRuntimeException(qex);
    } catch (RuntimeException rex) {
        if (rex.getCause() != null && rex.getCause().getMessage().contains(NO_SUITABLE_DRIVER)
                && WMAppContext.getInstance().isCloudFoundry()) {
            String msg = rex.getMessage() + " - " + UNKNOWN_DATABASE;
            throw new DataServiceRuntimeException(msg);
        } else {
            throw new DataServiceRuntimeException(rex);
        }
    } finally {
        try {
            ddlFile.delete();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.zeroone.guestebook.domain.SchemaGenerator.java

License:Apache License

/**
 * Method that actually creates the file.
 *
 * @return the generated {@link File}.//from  w w  w.  jav a 2 s.  c o  m
 */
public File generate(File directory) {
    SchemaExport export = new SchemaExport(metadata);
    export.setDelimiter(";");
    File file = new File(directory, String.format("ddl_%s.sql", dialect.name().toLowerCase()));
    export.setOutputFile(file.getAbsolutePath());
    export.setFormat(true);
    export.execute(true, false, false, false);
    return file;
}

From source file:de.jpdigital.maven.plugins.hibernate4ddl.GenerateDdlMojo.java

License:Open Source License

/**
 * Helper method for generating the DDL classes for a specific dialect. This
 * is place for the real work is done. The method first creates an instance
 * of the {@link Configuration} class from Hibernate an puts the appropriate
 * values into it. It then creates an instance of the {@link SchemaExport}
 * class from the Hibernate API, configured this class, for example by
 * setting {@code format} to {@code true} so that the generated SQL files
 * are formatted nicely. After that it calls the
 * {@link SchemaExport#execute(boolean, boolean, boolean, boolean)} method
 * which will create the SQL script file. The method is called in a way
 * which requires <em>no</em> database connection.
 *
 *
 * @param dialect       The dialect for which the DDL files is generated.
 * @param entityClasses The entity classes for which the DDL file is
 *                      generated./*from w w  w .  j  a v  a 2 s .c o m*/
 *
 * @throws MojoFailureException if something goes wrong.
 */
private void generateDdl(final Dialect dialect, final Set<Class<?>> entityClasses) throws MojoFailureException {
    final Configuration configuration = new Configuration();

    processPersistenceXml(configuration);

    configuration.setProperty("hibernate.hbm2ddl.auto", "create");

    for (final Class<?> entityClass : entityClasses) {
        configuration.addAnnotatedClass(entityClass);
    }

    configuration.setProperty("hibernate.dialect", dialect.getDialectClass());

    final SchemaExport export;
    if (useEnvers) {
        export = new EnversSchemaGenerator(configuration).export();
    } else {
        export = new SchemaExport(configuration);

    }
    export.setDelimiter(";");

    final Path tmpDir;
    try {
        tmpDir = Files.createTempDirectory("maven-hibernate-ddl-plugin");
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to create work dir.", ex);
    }
    export.setOutputFile(
            String.format("%s/%s.sql", tmpDir.toString(), dialect.name().toLowerCase(Locale.ENGLISH)));
    export.setFormat(true);
    export.execute(true, false, false, true);

    writeOutputFile(dialect, tmpDir);
}

From source file:de.jpdigital.maven.plugins.hibernate5ddl.GenerateDdlMojo.java

License:Open Source License

/**
 * Helper method for generating the DDL classes for a specific dialect. This
 * is place for the real work is done. The method first creates an instance
 * of the {@link Configuration} class from Hibernate an puts the appropriate
 * values into it. It then creates an instance of the {@link SchemaExport}
 * class from the Hibernate API, configured this class, for example by
 * setting {@code format} to {@code true} so that the generated SQL files
 * are formatted nicely. After that it calls the
 * {@link SchemaExport#execute(boolean, boolean, boolean, boolean)} method
 * which will create the SQL script file. The method is called in a way
 * which requires <em>no</em> database connection.
 *
 *
 * @param dialect       The dialect for which the DDL files is generated.
 * @param entityClasses The entity classes for which the DDL file is
 *                      generated./*from  w w w.  ja va 2s  .  c o m*/
 *
 * @throws MojoFailureException if something goes wrong.
 */
private void generateDdl(final Dialect dialect, final Set<Class<?>> entityClasses) throws MojoFailureException {

    final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
    processPersistenceXml(registryBuilder);

    if (createDropStatements) {
        registryBuilder.applySetting("hibernate.hbm2ddl.auto", "create-drop");
    } else {
        registryBuilder.applySetting("hibernate.hbm2ddl.auto", "create");
    }

    registryBuilder.applySetting("hibernate.dialect", dialect.getDialectClass());

    final StandardServiceRegistry standardRegistry = registryBuilder.build();

    final MetadataSources metadataSources = new MetadataSources(standardRegistry);

    for (final Class<?> entityClass : entityClasses) {
        metadataSources.addAnnotatedClass(entityClass);
    }

    final SchemaExport export = new SchemaExport();
    //        final SchemaExport export = new SchemaExport(
    //            (MetadataImplementor) metadata, true);
    export.setDelimiter(";");

    final Path tmpDir;
    try {
        tmpDir = Files.createTempDirectory("maven-hibernate5-ddl-plugin");
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to create work dir.", ex);
    }

    final Metadata metadata = metadataSources.buildMetadata();

    export.setOutputFile(
            String.format("%s/%s.sql", tmpDir.toString(), dialect.name().toLowerCase(Locale.ENGLISH)));
    export.setFormat(true);
    if (createDropStatements) {
        export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.BOTH, metadata);
    } else {
        export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadata);
    }

    writeOutputFile(dialect, tmpDir);
}