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

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

Introduction

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

Prototype

public SchemaExport setOutputFile(String filename) 

Source Link

Document

For generating a export script file, this is the file which will be written.

Usage

From source file:GenerateSchema.java

License:BSD License

/**
 * @param args//from w  ww . ja  v  a  2 s  .  c  o m
 */
public static void main(String[] args) {

    Configuration cfg = new Configuration().configure();
    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setFormat(true);
    schemaExport.setOutputFile("test.sql");
    schemaExport.create(true, false);
}

From source file:almira.sample.dao.ExportDatabaseSchemaTest.java

License:Apache License

@Test
public void exportDatabaseSchema() {
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
    Map<String, Object> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();

    Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
            .getHibernateConfiguration();

    SchemaExport schema = new SchemaExport(configuration);
    schema.setOutputFile("../conf/database/db-001-schema.sql");

    // BUG:/*from   w  ww  . j a  v a 2s  .  co  m*/
    // https://issues.jboss.org/browse/JBIDE-10558?page=com.atlassian.jira.plugin.system.issuetabpanels:changehistory-tabpanel
    schema.create(true, false);
}

From source file:be.fedict.eid.applet.maven.sql.ddl.SQLDDLMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("SQL DDL script generator");

    File outputFile = new File(this.outputDirectory, this.outputName);
    getLog().info("Output SQL DDL script file: " + outputFile.getAbsolutePath());

    this.outputDirectory.mkdirs();
    try {/*ww  w. ja v  a  2  s . c o m*/
        outputFile.createNewFile();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O error.", e);
    }

    for (ArtifactItem artifactItem : this.artifactItems) {
        getLog().info("artifact: " + artifactItem.getGroupId() + ":" + artifactItem.getArtifactId());
        List<Dependency> dependencies = this.project.getDependencies();
        String version = null;
        for (Dependency dependency : dependencies) {
            if (StringUtils.equals(dependency.getArtifactId(), artifactItem.getArtifactId())
                    && StringUtils.equals(dependency.getGroupId(), artifactItem.getGroupId())) {
                version = dependency.getVersion();
                break;
            }
        }
        getLog().info("artifact version: " + version);
        VersionRange versionRange = VersionRange.createFromVersion(version);
        Artifact artifact = this.artifactFactory.createDependencyArtifact(artifactItem.getGroupId(),
                artifactItem.getArtifactId(), versionRange, "jar", null, Artifact.SCOPE_COMPILE);
        try {
            this.resolver.resolve(artifact, this.remoteRepos, this.local);
        } catch (ArtifactResolutionException e) {
            throw new MojoExecutionException("Unable to resolve artifact.", e);
        } catch (ArtifactNotFoundException e) {
            throw new MojoExecutionException("Unable to find artifact.", e);
        }
        getLog().info("artifact file: " + artifact.getFile().getAbsolutePath());
        getLog().info("hibernate dialect: " + this.hibernateDialect);

        URL artifactUrl;
        try {
            artifactUrl = artifact.getFile().toURI().toURL();
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("URL error.", e);
        }

        URLClassLoader classLoader = new URLClassLoader(new URL[] { artifactUrl },
                this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(classLoader);

        AnnotationDB annotationDb = new AnnotationDB();
        try {
            annotationDb.scanArchives(artifactUrl);
        } catch (IOException e) {
            throw new MojoExecutionException("I/O error.", e);
        }
        Set<String> classNames = annotationDb.getAnnotationIndex().get(Entity.class.getName());
        getLog().info("# JPA entity classes: " + classNames.size());

        AnnotationConfiguration configuration = new AnnotationConfiguration();

        configuration.setProperty("hibernate.dialect", this.hibernateDialect);
        Dialect dialect = Dialect.getDialect(configuration.getProperties());
        getLog().info("dialect: " + dialect.toString());

        for (String className : classNames) {
            getLog().info("JPA entity: " + className);
            Class<?> entityClass;
            try {
                entityClass = classLoader.loadClass(className);
                getLog().info("entity class loader: " + entityClass.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException("class not found.", e);
            }
            configuration.addAnnotatedClass(entityClass);
        }

        SchemaExport schemaExport = new SchemaExport(configuration);
        schemaExport.setFormat(true);
        schemaExport.setHaltOnError(true);
        schemaExport.setOutputFile(outputFile.getAbsolutePath());
        schemaExport.setDelimiter(";");

        try {
            getLog().info("SQL DDL script: " + IOUtil.toString(new FileInputStream(outputFile)));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("file not found.", e);
        } catch (IOException e) {
            throw new MojoExecutionException("I/O error.", e);
        }

        // operate
        schemaExport.execute(true, false, false, true);
        List<Exception> exceptions = schemaExport.getExceptions();
        for (Exception exception : exceptions) {
            getLog().error("exception: " + exception.getMessage());
        }
    }
}

From source file:be.fedict.eid.pkira.blm.hibernateutil.SchemaGenerator.java

License:Open Source License

/**
 * Method that actually creates the file.
 * /*from ww w.  j  ava  2  s  . c om*/
 * @param dbDialect
 *            to use
 */
private void generate(Dialect dialect) {
    new java.io.File(workingDir + "/schema").mkdirs();

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

    SchemaExport export = new SchemaExport(cfg);
    export.setDelimiter(";");
    export.setOutputFile(workingDir + "/schema/ddl_" + dialect.name().toLowerCase() + ".sql");
    export.execute(true, false, false, false);
}

From source file:bookpub.util.Hbm2ddl.java

License:Open Source License

public static void main(String args[]) {
    if (args.length == 0) {
        System.err.println("java Hbm2ddl <outputFile>");
        return;/*  w w  w  .  j a  va  2  s.co m*/
    }

    System.out.print("Export DDL to " + args[0] + " ... ");

    Configuration cfg = (new Ejb3Configuration()).configure("bookpub", new HashMap<String, Object>())
            .getHibernateConfiguration();

    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setOutputFile(args[0]).setDelimiter(";").setFormat(true).setHaltOnError(true);

    // . output script to console (and file if outputFile is set): true
    // . export to database: false
    // . only drop the tables: false
    // . only create the tables: true
    schemaExport.execute(true, false, false, true);

    System.out.println("Done.");
}

From source file:br.com.machina.verbum.Main.java

License:Apache License

private static void generateTables() {

    AnnotationConfiguration configuration = new AnnotationConfiguration();
    configuration.configure();/*from   www . j  ava 2s. c o m*/

    SchemaExport export = new SchemaExport(configuration);
    export.setDelimiter(";");
    export.setOutputFile("tables.sql");
    export.create(true, true);
    System.out.println("Ok!");

}

From source file:ch.qos.logback.audit.server.TableCreator.java

License:Open Source License

public void createTables(String filename) {
    SchemaExport schemaExport = new SchemaExport(cfg);
    boolean printDLL = false;
    if (filename != null) {
        schemaExport.setOutputFile(filename);
        printDLL = true;//w  ww  .  ja  va 2s .  c om
    }

    schemaExport.create(printDLL, true);

}

From source file:com.ah.util.HibernateUtil.java

public static void main(String[] args) {
    init(false);//from  w ww  .  j a v a 2 s . c om
    System.out.println("Entered HibernateUtil.main");
    System.out.println("# arguments: " + Arrays.asList(args));
    System.out.println("Getting configuration.");

    if ("create".equals(args[0])) {
        if (args.length >= 2) {
            String newUrl = "jdbc:postgresql://localhost/" + args[1];
            configuration.setProperty("hibernate.connection.url", newUrl);

            if (args.length >= 3) {
                try {
                    int i = Integer.parseInt(args[2]);

                    if ((1 == i) && (BeOperateHMCentOSImpl.isExistHomeDomain())) {
                        System.out.println("have tables! need not recreate");

                        return;
                    }
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        }

        SchemaExport schemaExport = new SchemaExport(configuration);

        System.out.println("Creating schema ...");
        schemaExport.create(true, true);
        //   BeSqlProcedure.insertSqlProcedure();
        DBFunction.createHex2Int();
        DBFunction.createDBRollUp();
        DBFunction.createRepoRollUp();
        System.out.println("Create schema finished.");
    } else if ("export".equals(args[0])) {
        SchemaExport schemaExport = new SchemaExport(configuration);

        schemaExport.setOutputFile("schema.ddl");
        schemaExport.setDelimiter(";");
        System.out.println("Exporting schema ...");
        schemaExport.create(true, false);
        System.out.println("Export finished.");
    } else if ("drop".equals(args[0])) {
        SchemaExport schemaExport = new SchemaExport(configuration);

        System.out.println("Dropping schema ...");
        schemaExport.drop(true, true);
        System.out.println("Drop schema finished.");
    } else if ("reset".equals(args[0])) {
        //java HibernateUtil reset jdbc:postgresql://ip_address/db_name
        if (args.length >= 2) {
            configuration.setProperty("hibernate.connection.url", args[1]);
        }
        SchemaExport schemaExport = new SchemaExport(configuration);
        schemaExport.create(true, true);
        DBFunction.createHex2Int();
        DBFunction.createDBRollUp();
        DBFunction.createRepoRollUp();
        System.out.println("execute reset finished.");
    }

    close();
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

private void traceDDL() {
    try {//from w  w  w. java 2  s. com
        if (configuration == null) {
            throw new IllegalStateException("Expect a Hibernate configuration to be set."); //$NON-NLS-1$
        }
        String jbossServerTempDir = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
        RDBMSDataSource.DataSourceDialect dialectType = dataSource.getDialectName();
        SchemaExport export = new SchemaExport(configuration);
        export.setFormat(false);
        String filename = jbossServerTempDir + File.separator + storageName + "_" + storageType + "_" //$NON-NLS-1$//$NON-NLS-2$
                + dialectType + ".ddl"; //$NON-NLS-1$
        export.setOutputFile(filename);
        export.setDelimiter(";"); //$NON-NLS-1$
        export.execute(false, false, false, true);
        if (export.getExceptions().size() > 0) {
            for (int i = 0; i < export.getExceptions().size(); i++) {
                LOGGER.error("Error occurred while producing ddl.", //$NON-NLS-1$
                        (Exception) export.getExceptions().get(i));
            }
        }
        LOGGER.info("DDL exported to file '" + filename + "'."); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        LOGGER.error("Error occurred while producing ddl.", e); //$NON-NLS-1$
    }
}

From source file:com.comcast.cats.recorder.persistence.SqlTableCreator.java

License:Open Source License

/**
 * Method that actually creates the file.
 * /*w  w  w . j  a v  a2s .  c  om*/
 * @param dbDialect
 *            to use
 */
private void generate(Dialect dialect) {
    cfg.setProperty("hibernate.dialect", dialect.getDialectClass());

    SchemaExport export = new SchemaExport(cfg);
    export.setDelimiter(";");
    export.setOutputFile("ddl_" + dialect.name().toLowerCase() + ".sql");
    export.execute(true, false, false, false);
}