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:org.infoglue.calendar.controllers.SchemaExportController.java

License:Open Source License

public void exportTables() throws HibernateException {
    Configuration cfg = new Configuration().addClass(Calendar.class).addClass(Location.class)
            .addClass(Category.class).addClass(Participant.class).addClass(Resource.class)
            .addClass(Event.class);

    cfg.setProperty("hibernate.dialect", "net.sf.hibernate.dialect.MySQLDialect");
    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setOutputFile("calendar.sql");
    schemaExport.create(true, true);/*w w  w.  ja  va 2  s . c  o m*/
}

From source file:org.jahia.maven.hbm2ddl.JpaSchemaExportMojo.java

License:Open Source License

private void performExport() throws MojoExecutionException {
    final Configuration cfg = new Ejb3Configuration().configure(persistenceUnitName, getHibernateProperties())
            .getHibernateConfiguration();

    configureNamingStrategy(cfg);/*  w  ww  .j  a va  2  s .c  o m*/

    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setDelimiter(";");
    schemaExport.setOutputFile(outputFile.getAbsolutePath());
    schemaExport.execute(Target.SCRIPT, statementType);
}

From source file:org.jboss.bpm.monitor.model.hibernate.SchemaGenerator.java

License:Apache License

/**
 * Method that actually creates the file.
 */// w  w  w . j  av a  2 s  .  co m
private void generate(Dialect dialect) {
    String s = output.getAbsolutePath() + "/ddl_" + dialect.name().toLowerCase() + ".sql";
    cfg.setProperty("hibernate.dialect", dialect.getDialectClass());

    SchemaExport export = new SchemaExport(cfg);
    export.setDelimiter(";");
    export.setOutputFile(s);
    export.setFormat(true);
    export.setHaltOnError(true);
    export.execute(true, false, false, false);

    System.out.println("==================");
    System.out.println("DDL: " + s);
    System.out.println("==================");
}

From source file:org.jbpm.ant.JbpmSchemaTask.java

License:Open Source License

public void execute() throws BuildException {
    if (actions == null) {
        // default action is create
        actions = "create";
    }//w  w w .j a  v a  2  s .c  o m

    // we need a configuration
    Configuration configuration = null;

    // if there is no jbpm nor hibernate configuration specified
    if ((jbpmCfg == null) && (hibernateCfg == null)) {
        // search for the default jbpm.cfg.xml
        URL defaultJbpmCfgUrl = getClass().getClassLoader().getResource("jbpm.cfg.xml");
        if (defaultJbpmCfgUrl != null) {
            jbpmCfg = "jbpm.cfg.xml";
            // if still not found, search for the default hibernate.cfg.xml
        } else {
            URL defaultHibernateCfgUrl = getClass().getClassLoader().getResource("hibernate.cfg.xml");
            if (defaultHibernateCfgUrl != null) {
                hibernateCfg = "hibernate.cfg.xml";
            }
        }
    }

    // first see if the jbpm cfg is specified cause that implies a hibernate configuration
    if (jbpmCfg != null) {
        log("using jbpm configuration " + jbpmCfg);
        JbpmConfiguration jbpmConfiguration = AntHelper.getJbpmConfiguration(jbpmCfg);
        JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
        try {
            DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) jbpmConfiguration
                    .getServiceFactory(Services.SERVICENAME_PERSISTENCE);
            configuration = dbPersistenceServiceFactory.getConfiguration();
        } finally {
            jbpmContext.close();
        }

        // if there is no jbpm.cfg.xml specified, check if there is a hibernate.cfg.xml specified
    } else if (hibernateCfg != null) {
        log("using hibernate configuration " + hibernateCfg);
        configuration = AntHelper.getConfiguration(hibernateCfg, hibernateProperties);

        // no hibernate configuration specified
    } else {
        throw new BuildException("couldn't create schema.  no jbpm nor hibernate configuration specified.");
    }

    JbpmSchema jbpmSchema = new JbpmSchema(configuration);

    SchemaExport schemaExport = new SchemaExport(configuration);
    if (output != null)
        schemaExport.setOutputFile(output);
    if (delimiter != null)
        schemaExport.setDelimiter(delimiter);

    StringTokenizer tokenizer = new StringTokenizer(actions, ",");
    while (tokenizer.hasMoreTokens()) {
        String action = tokenizer.nextToken();

        if ("drop".equalsIgnoreCase(action)) {
            schemaExport.drop(!quiet, !text);

        } else if ("create".equalsIgnoreCase(action)) {
            schemaExport.create(!quiet, !text);

        } else if ("clean".equalsIgnoreCase(action)) {
            jbpmSchema.cleanSchema();
        }
    }
}

From source file:org.jpos.ee.DB.java

License:Open Source License

/**
 * Creates database schema/*from w  w  w  . j a  va 2 s .c  o  m*/
 *
 * @param outputFile optional output file (may be null)
 * @param create     true to actually issue the create statements
 */
public void createSchema(String outputFile, boolean create) throws HibernateException {
    SchemaExport export = new SchemaExport(getHibernateAccessService().getConfiguration());
    if (outputFile != null) {
        export.setOutputFile(outputFile);
        export.setDelimiter(";");
    }
    export.create(true, create);
}

From source file:org.kuali.mobility.shared.controllers.HomeController.java

License:Open Source License

/**
 * Controller method to download a ddl.//from w ww.j a  v  a2  s  . c  o m
 */
@Deprecated
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "ddl", method = RequestMethod.GET)
public void exportDatabaseSchema(HttpServletRequest request, HttpServletResponse response, Model uiModel) {
    PersistenceUnitInfo persistenceUnitInfo = getEntityManagerFactory().getPersistenceUnitInfo();

    Map jpaPropertyMap = getEntityManagerFactory().getJpaPropertyMap();
    jpaPropertyMap.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
            .getHibernateConfiguration();

    SchemaExport schema = new SchemaExport(configuration);
    schema.setFormat(true);
    schema.setDelimiter(";");
    schema.setOutputFile("/tmp/schema.sql");
    schema.create(false, false);
}

From source file:org.ngrinder.infra.init.DataUpdaterTest.java

License:Apache License

@Test
public void exportDatabaseSchema() throws IOException {
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
    for (Database each : Database.values()) {
        Map<?, ?> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();
        Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
                .getHibernateConfiguration();
        configuration.setProperty(Environment.DIALECT, each.getDialect());
        SchemaExport schema = new SchemaExport(configuration);
        File parentFile = new ClassPathResource("/ngrinder_datachange_logfile/db.changelog.xml").getFile()
                .getParentFile();/*www . ja  va 2  s  .  co m*/

        parentFile.mkdirs();
        File file = new File(parentFile, "schema-" + each.name().toLowerCase() + ".sql");
        System.out.println(file.getAbsolutePath());
        schema.setOutputFile(file.getAbsolutePath());
        schema.create(true, false);
    }
}

From source file:org.olat.core.commons.persistence.DatabaseSetup.java

License:Apache License

/**
 * Write database configuration to file. Includes differences to existing database. Filename: "database/setupDatabase.sql"
 *//*from   w  w  w  .j a v a2 s . c o m*/
private static void exportDDLtoFile() {
    String outputFile = "database/setupDatabase.sql";

    boolean script = true; // write DDL
    boolean export = false; // don't update databse
    try {
        SchemaExport se = new SchemaExport(cf);
        se.setOutputFile(outputFile);
        se.setDelimiter(";");
        se.create(script, export);
    } catch (Exception e) {
        log.error("DDL export to file failed: Reason: ", e);
    }
}

From source file:org.openbp.server.persistence.hibernate.HibernateDDLGenerator.java

License:Apache License

/**
 * Generates the DDL files./*  w ww. j  a  v  a  2s .co m*/
 */
public void generate() {
    ProcessServer processServer = new ProcessServerFactory().createProcessServer();

    PersistenceContextProvider provider = processServer.getEngine().getPersistenceContextProvider();
    if (provider == null) {
        String msg = LogUtil.error(getClass(), "No persistence context provider configured.");
        System.err.println(msg);
        System.exit(1);
        return;
    }
    if (!(provider instanceof HibernatePersistenceContextProvider)) {
        String msg = LogUtil.error(getClass(),
                "Configured persistence context provider no no Hibernate provider (class $0).",
                provider.getClass().getName());
        System.err.println(msg);
        System.exit(1);
        return;
    }

    Configuration configuration = ((HibernatePersistenceContextProvider) provider)
            .createHibernateConfiguration();

    if (dialect != null) {
        String adapterClassName = null;
        if (dialect.indexOf('.') >= 0) {
            adapterClassName = dialect;
        } else {
            adapterClassName = "org.hibernate.dialect." + dialect + "Dialect";
        }
        configuration.setProperty("hibernate.dialect", adapterClassName);
    }

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

    String outputFile;

    if ((outputFile = prepareOutputFile(getDdlCreateFileName())) != null) {
        se.setOutputFile(outputFile);
        se.execute(false, false, false, true);
    }

    if ((outputFile = prepareOutputFile(getDdlDropFileName())) != null) {
        se.setOutputFile(outputFile);
        se.execute(false, false, true, false);
    }
}

From source file:org.opentides.persistence.hibernate.MultiTenantSchemaUpdate.java

License:Apache License

/**
 * This is the helper function that initializes the schema and tables.
 * Initialization is as follows: /*from w w  w .  j a  v a2s  .  c om*/
 *    (1) Get the latest initialization sql script. Execute the sql script.
 *    (2) If there is no initialization script, use the hibernate SchemaExport.
 *    
 * @param tenantId
 */
private void initializeSchema(Configuration cfg, Connection connection, String schema) {
    // check if there SQL file under the sslScript folder
    boolean initialized = false;

    if (ddlScript != null && ddlScript.exists()) {
        _log.info("Initializing schema [" + schema + "] using DDL script [" + ddlScript.getFilename() + "].");
        InputStream inputStream = null;
        try {
            inputStream = ddlScript.getInputStream();
            Scanner f = new Scanner(inputStream);
            StringBuilder stmt = new StringBuilder();
            while (f.hasNext()) {
                String line = f.nextLine();
                // ignore comment
                if (line.startsWith("--"))
                    continue;
                stmt.append(" ").append(line);
                if (line.endsWith(";")) {
                    // end of statement, execute then clear
                    connection.createStatement().execute(stmt.toString());
                    System.out.println(stmt.toString());
                    stmt.setLength(0);
                }
            }
            f.close();
            initialized = true;
        } catch (SQLException e) {
            _log.error("Failed to execute sql script for initialization", e);
        } catch (IOException e) {
            _log.error("Failed to read sql script for initialization", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (!initialized) {
        _log.info("Initializing schema [" + schema + "] using SchemaExport. ");
        SchemaExport export = new SchemaExport(cfg, connection);
        if (this.logDdl) {
            String dir = ddlLogs + "/" + DateUtil.convertShortDate(new Date());
            _log.info("DDL logs can be found in " + dir + "/schema-" + schema + ".sql");
            FileUtil.createDirectory(dir);
            export.setOutputFile(dir + "/schema-" + schema + ".sql");
            export.setDelimiter(";");
        }
        export.execute(this.logDdl, true, false, true);
    }

}