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

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

Introduction

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

Prototype

public void create(EnumSet<TargetType> targetTypes, Metadata metadata) 

Source Link

Usage

From source file:com.ironiacorp.persistence.hibernate.HibernateBootstrap.java

License:Open Source License

/**
 * Create the database.//from  w ww.j a va  2  s . co m
 * 
 * @throws RuntimeException
 *             If an error is found when running the DDL script.
 */
public void createDB() {
    log.debug("Creating the database");
    log.debug(getCreateDDLScript());
    SchemaExport ddl = new SchemaExport(config);
    List<Exception> exceptions = null;

    ddl.create(false, true);
    exceptions = handleExceptions(ddl);
    if (!exceptions.isEmpty()) {
        throw new RuntimeException("exception.bootstrap.createdb", (Exception) ddl.getExceptions().get(0));
    }
}

From source file:com.klistret.cmdb.utility.hibernate.CMDBDatabaseHelper.java

License:Open Source License

public void generateDatabaseSchema(String path, boolean display, boolean execute) {
    SchemaExport sSchemaExport = new SchemaExport(CMDBDatabaseHelper.sConfiguration);
    sSchemaExport.setOutputFile(path);//  w ww .  j  a  va  2  s  . c om
    sSchemaExport.setDelimiter(delimiter);
    sSchemaExport.create(display, execute);
}

From source file:com.manning.junitbook.ch18.AbstractJpaTestCase.java

License:Apache License

protected void analyzeSchema(SqlHandler handler) {
    ConfigurationCreator cfgCreator = new ConfigurationCreator();
    Configuration cfg = cfgCreator.createConfiguration();
    SchemaExport export = new SchemaExport(cfg);

    // life would be much easier if Hibernate accepted a Writer on
    // export...//from ww w .  ja  v a  2 s.c  o  m
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream oldOut = System.out;
    PrintStream newOut = new PrintStream(outputStream);
    System.setOut(newOut);
    try {
        export.create(true, true);
        final String sql = outputStream.toString();
        handler.handle(sql);
    } finally {
        System.setOut(oldOut);
        newOut.close();
    }

}

From source file:com.medigy.tool.persist.hibernate.ddl.GenerateDDLTask.java

License:Open Source License

public void execute() throws BuildException {
    if (hibernateConfigClass == null)
        throw new BuildException("hibernateConfigClass was not provided.");

    if (destDir == null)
        throw new BuildException("destDir was not provided.");

    try {/*from w  w w . j av a2 s  .c  o m*/
        final SqlDataDefinitionFilter createFilter = (SqlDataDefinitionFilter) createSqlDataDefinitionFilterClass
                .newInstance();
        log("Using create DDL filter " + createFilter.getClass().getName());

        final SqlDataDefinitionFilter cleanFilter = (SqlDataDefinitionFilter) cleanSqlDataDefinitionFilterClass
                .newInstance();
        log("Using clean DDL filter " + createFilter.getClass().getName());

        final Configuration configuration = (Configuration) hibernateConfigClass.newInstance();
        log("Using configuration " + configuration.getClass().getName());

        if (hibernateConfigFile != null) {
            configuration.configure(hibernateConfigFile);
            log("Using configuration file " + hibernateConfigFile);
        }

        final Class[] dialects = HibernateDialectsCatalog.getDialects();
        for (int i = 0; i < dialects.length; i++) {
            final Class dialectClass = dialects[i];
            final Dialect dialect = (Dialect) dialectClass.newInstance();
            final String dialectClassName = dialectClass.getName();
            final String dialectShortName = dialectClass.getName()
                    .substring(dialectClassName.lastIndexOf('.') + 1);
            final File dialectFile = new File(dialectShortName + destFileExtension);

            final Properties properties = new Properties();
            properties.put(Environment.DIALECT, dialectClass.getName());

            final File createFileFiltered = new File(destDir, createPrefix + dialectFile);
            final File createFileTmp = File.createTempFile(getClass().getName() + "-",
                    "-" + createPrefix + dialectFile);
            createFileTmp.deleteOnExit();

            final File cleanFileFiltered = new File(destDir, cleanPrefix + dialectFile);
            final File cleanFileTmp = File.createTempFile(getClass().getName() + "-",
                    "-" + cleanPrefix + dialectFile);
            cleanFileTmp.deleteOnExit();

            final SchemaExport exporter;
            try {
                // Generates CREATE statements including, quite stupidly, DROP statements which we'll filter later
                exporter = new SchemaExport(configuration, properties);
                exporter.setDelimiter(sqlStmtDelimiter);
                exporter.setOutputFile(createFileTmp.getAbsolutePath());
                exporter.create(false, false);

                // Generates DROP statements only
                exporter.setOutputFile(cleanFileTmp.getAbsolutePath());
                exporter.drop(false, false);
            } catch (HibernateException e) {
                log("Error generating DDL for " + dialectClassName + ": " + e.getMessage());
                continue;
            }

            final SqlDataDefinitionFilterProcessor createFilterProcessor = new SqlDataDefinitionFilterProcessor(
                    createFilter, configuration, dialect, createFileTmp, createFileFiltered, sqlStmtDelimiter);
            createFilterProcessor.execute();

            final SqlDataDefinitionFilterProcessor cleanFilterProcessor = new SqlDataDefinitionFilterProcessor(
                    cleanFilter, configuration, dialect, cleanFileTmp, cleanFileFiltered, sqlStmtDelimiter);
            cleanFilterProcessor.execute();

            log("Generated create " + dialectShortName + " DDL in " + createFileFiltered.getAbsolutePath()
                    + " (" + createFilterProcessor.getRemovedLines() + " lines removed, "
                    + createFilterProcessor.getReplacedLines() + " lines replaced)");
            log("Generated clean " + dialectShortName + " DDL in " + cleanFileFiltered.getAbsolutePath() + " ("
                    + cleanFilterProcessor.getRemovedLines() + " lines removed, "
                    + cleanFilterProcessor.getReplacedLines() + " lines replaced)");
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}

From source file:com.mycompany.testes.TesteTrocarConfiguracao.java

public static void main(String[] args) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Usuario usuario = null;/*  w  ww.  j a  v  a 2 s .  c o  m*/

    session.beginTransaction();

    Query query = session
            .createQuery("from Usuario u WHERE u.userName = 'mvassoler' and u.passwordUser = 'mitco'");
    usuario = (Usuario) query.uniqueResult();

    session.getSessionFactory().close();

    System.out.println(usuario.getName());

    Configuration config = new Configuration().configure("hibernate.cfgGen.xml");
    config.setProperty("connection.driver_class", usuario.getDriverClass());
    config.setProperty("connection.url", usuario.getUrl() + usuario.getDataBase());
    config.setProperty("hibernate.dialect", usuario.getDialect());
    SchemaExport se = new SchemaExport(config);
    se.create(true, true);
}

From source file:com.netspective.medigy.model.TestCase.java

License:Open Source License

protected void setUp() throws Exception {
    System.out.println("here in setup");
    super.setUp();

    final String systemTempDir = System.getProperty("java.io.tmpdir");
    final String systemFileSep = System.getProperty("file.separator");

    final String testDbDir = System.getProperty("project.test.db.dir", systemTempDir);

    databaseDirectory = new File(testDbDir + systemFileSep + getClassNameWithoutPackage());
    System.out.println("Database directory: " + databaseDirectory.getAbsolutePath());
    loadServiceLocator();//from  w w  w . j  a v  a  2  s  .com

    final HibernateConfiguration hibernateConfiguration = getHibernateConfiguration();
    HibernateUtil.setConfiguration(hibernateConfiguration);

    if (initializeModelData)
        new ModelInitializer(HibernateUtil.getSession(), ModelInitializer.SeedDataPopulationType.AUTO,
                hibernateConfiguration).initialize();

    // Generate the DDL into a file so we can review it
    SchemaExport se = new SchemaExport(hibernateConfiguration);
    final String dialectName = hibernateConfiguration.getProperties().getProperty(Environment.DIALECT);
    final String dialectShortName = dialectName.substring(dialectName.lastIndexOf('.') + 1);
    se.setOutputFile(
            databaseDirectory.getAbsolutePath() + systemFileSep + "medigy-" + dialectShortName + ".ddl");
    se.create(false, false);

    // setup a person here so that we can add a contact information for him/her
    Session session = new ProcessSession();
    session.setProcessName(getClass().getName() + "." + getName());
    SessionManager.getInstance().pushActiveSession(session);
    HibernateUtil.getSession().save(session);
}

From source file:com.persinity.ndt.datamutator.hibernate.HibernateEntityFactory.java

License:Apache License

@Override
public void initSchema() {
    assertState(configuration != null, "You should call init() before use");

    // hack to not dump the schema init at System.out
    final String res = executeAndCaptureSysOut(new Function<Void, Void>() {
        @Override//from   www .ja va2 s .c  o m
        public Void apply(final Void aVoid) {
            SchemaExport schemaExport = new SchemaExport(configuration);
            schemaExport.create(true, true);
            return null;
        }
    });
    log.info("{}", res);
}

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);/*from  w  ww  .j  a  v a 2  s  .  com*/
    schemaExport.setOutputFile("createSchema.sql");
    schemaExport.create(true, false);
}

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);//from  w w w. j av a  2  s.  co  m
    final File f = new File("src/main/scripts");
    f.mkdirs();
    schemaExport.setOutputFile("src/main/scripts/schema.sql");
    schemaExport.drop(true, true);
    schemaExport.create(true, true);
}

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

License:Open Source License

@Override
protected void customRun() {

    init();/*from  ww  w  .  j av 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) {
        }
    }
}