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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public void execute(EnumSet<TargetType> targetTypes, Action action, Metadata metadata,
            ServiceRegistry serviceRegistry) 

Source Link

Usage

From source file:org.apache.juddi.ddl.generator.App.java

License:Apache License

/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use/*from   w ww . ja va2  s  .  c  o  m*/
 */
private void generate(Dialect dialect) {
    cfg.setProperty("hibernate.dialect", dialect.getDialectClass());

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

From source file:org.beangle.commons.orm.hibernate.ddl.DdlGenerator.java

License:Open Source License

public void gen(String dialect, String fileName) throws HibernateException, IOException {
    Configuration configuration = new OverrideConfiguration();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            DdlGenerator.class.getClassLoader());

    configuration.getProperties().put(Environment.DIALECT, dialect);

    // config naming strategy
    DefaultTableNamingStrategy tableNamingStrategy = new DefaultTableNamingStrategy();
    for (Resource resource : resolver.getResources("classpath*:META-INF/beangle/table.properties"))
        tableNamingStrategy.addConfig(resource.getURL());
    RailsNamingStrategy namingStrategy = new RailsNamingStrategy();
    namingStrategy.setTableNamingStrategy(tableNamingStrategy);
    configuration.setNamingStrategy(namingStrategy);

    for (Resource resource : resolver.getResources("classpath*:META-INF/hibernate.cfg.xml"))
        configuration.configure(resource.getURL());
    SchemaExport export = new SchemaExport(configuration);
    export.setOutputFile(fileName);//  w ww .j a va  2s  . c o  m
    export.execute(false, false, false, true);
}

From source file:org.bedework.calcore.hibernate.SchemaBuilderImpl.java

License:Apache License

@Override
public void execute(final Properties props, final String outputFile, final boolean export,
        final String delimiter) throws CalFacadeException {
    try {/*from  w  w w  .  j  a va  2 s  .  com*/
        SchemaExport se = new SchemaExport(getConfiguration(props));

        if (delimiter != null) {
            se.setDelimiter(delimiter);
        }

        se.setFormat(true);
        se.setHaltOnError(false);
        se.setOutputFile(outputFile);

        se.execute(false, // script - causes write to System.out if true
                export, false, // drop
                true); // create
    } catch (Throwable t) {
        throw new CalFacadeException(t);
    }
}

From source file:org.bedework.synch.service.Synch.java

License:Apache License

@Override
public String schema() {
    String result = "Export complete: check logs";

    try {//  ww  w  .j a va2s .c  o  m
        SchemaExport se = new SchemaExport(getConfiguration());

        if (getDelimiter() != null) {
            se.setDelimiter(getDelimiter());
        }

        se.setFormat(getFormat());
        se.setHaltOnError(getHaltOnError());
        se.setOutputFile(getSchemaOutFile());
        se.setImportFile(getSqlIn());

        se.execute(false, // script - causes write to System.out if true
                getExport(), getDrop(), getCreate());
    } catch (Throwable t) {
        error(t);
        result = "Exception: " + t.getLocalizedMessage();
    } finally {
        create = false;
        drop = false;
        export = false;
    }

    return result;
}

From source file:org.codehaus.mojo.hibernate3.exporter.Hbm2DDLExporterMojo.java

License:Apache License

/**
 * Overrides the default implementation of executing this goal.
 *
 * @throws MojoExecutionException if there is an error executing the goal
 *//*from w  w  w  . j a v  a  2s . c  o  m*/
protected void doExecute() throws MojoExecutionException {
    boolean scriptToConsole = getComponentProperty("console", true);
    boolean exportToDatabase = getComponentProperty("export", true);
    boolean haltOnError = getComponentProperty("haltonerror", false);
    boolean drop = getComponentProperty("drop", false);
    boolean create = getComponentProperty("create", true);
    String implementation = getComponentProperty("implementation", getComponent().getImplementation());

    Configuration configuration = getComponentConfiguration(implementation).getConfiguration(this);

    if (getComponentProperty("update", false)) {
        SchemaUpdate update = new SchemaUpdate(configuration);
        update.execute(scriptToConsole, exportToDatabase);
    } else {
        SchemaExport export = new SchemaExport(configuration);
        export.setDelimiter(getComponentProperty("delimiter", ";"));
        export.setHaltOnError(haltOnError);
        export.setFormat(getComponentProperty("format", false));

        String outputFilename = getComponentProperty("outputfilename");
        if (outputFilename != null) {
            File outputFile = HibernateUtils.prepareFile(
                    new File(getProject().getBasedir(), getComponent().getOutputDirectory()), outputFilename,
                    "outputfilename");
            export.setOutputFile(outputFile.toString());
        }

        if (drop && create) {
            export.create(scriptToConsole, exportToDatabase);
        } else {
            export.execute(scriptToConsole, exportToDatabase, drop, create);
        }

        if (export.getExceptions().size() > 0) {
            Iterator iterator = export.getExceptions().iterator();
            int cnt = 1;
            getLog().warn(export.getExceptions().size() + " errors occurred while performing <hbm2ddl>.");
            while (iterator.hasNext()) {
                getLog().error("Error #" + cnt + ": " + iterator.next().toString());
            }
            if (haltOnError) {
                throw new MojoExecutionException("Errors while performing <hbm2ddl>");
            }
        }
    }
}

From source file:org.jasig.portlet.announcements.SchemaCreator.java

License:Apache License

private int create() {

    /*//w  w  w  .  jav  a2s.c o  m
     * We will need to provide a Configuration and a Connection;  both should be properly
     * managed by the Spring ApplicationContext.
     */

    final LocalSessionFactoryBean sessionFactoryBean = applicationContext.getBean(SESSION_FACTORY_BEAN_NAME,
            LocalSessionFactoryBean.class);
    final DataSource dataSource = applicationContext.getBean(DATA_SOURCE_BEAN_NAME, DataSource.class);

    try (final Connection conn = dataSource.getConnection()) {
        final Configuration cfg = sessionFactoryBean.getConfiguration();
        final SchemaExport schemaExport = new SchemaExport(cfg, conn);
        schemaExport.execute(true, true, false, false);

        final List<Exception> exceptions = schemaExport.getExceptions();
        if (exceptions.size() != 0) {
            logger.error("Schema Create Failed;  see below for details");
            for (Exception e : exceptions) {
                logger.error("Exception from Hibernate Tools SchemaExport", e);
            }
            return 1;
        }
    } catch (SQLException sqle) {
        logger.error("Failed to initialize & invoke the SchemaExport tool", sqle);
        return 1;
    }

    return 0;

}

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

License:Apache License

/**
 * Method that actually creates the file.
 *///from   www  .  j  a va  2s.c o  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.openbp.server.persistence.hibernate.HibernateDDLGenerator.java

License:Apache License

/**
 * Generates the DDL files./*from  w  w  w  . j ava 2s  .  com*/
 */
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. jav a2  s. c o  m
 *    (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);
    }

}

From source file:org.spliffy.server.db.utils.SchemaExporter.java

License:Open Source License

/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use/*from w  ww .  j av a  2  s.c  o  m*/
 */
public void generate() throws Exception {
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    AnnotationConfiguration cfg;
    cfg = new AnnotationConfiguration();
    cfg.setProperty("hibernate.hbm2ddl.auto", "create");
    cfg.setNamingStrategy(new org.hibernate.cfg.ImprovedNamingStrategy());

    for (Class<Object> clazz : getClasses(packageName)) {
        cfg.addAnnotatedClass(clazz);
    }
    for (Dialect d : Dialect.values()) {
        cfg.setProperty("hibernate.dialect", d.getDialectClass());
        SchemaExport export = new SchemaExport(cfg);
        export.setDelimiter(";");
        File fOut = new File(outputDir, d.name().toLowerCase() + ".sql");
        export.setOutputFile(fOut.getAbsolutePath());
        export.execute(true, false, false, false);
    }
}