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:net.firejack.platform.core.utils.SchemaGenerator.java

License:Apache License

/**
 * Generates database schema from given application config resources
 *
 * @param configResources        - list of application config resources with mapped hibernates entities
 * @param propertyFileName       - placeholder property file
 * @param outputFileName         - output sql schema file name
 * @param sessionFactoryBeanName - spring session factory bean name
 *///from   ww w .j  a va2s . c  om
public void generateSchema(String[] configResources, String propertyFileName, String outputFileName,
        String sessionFactoryBeanName) {
    AbstractApplicationContext appContext = new ClassPathXmlApplicationContext(configResources, false);
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    Resource res = new ClassPathResource("/" + propertyFileName);
    ppc.setLocation(res);
    appContext.addBeanFactoryPostProcessor(ppc);
    appContext.refresh();
    LocalSessionFactoryBean sessionFactory;
    try {
        sessionFactory = appContext.getBean("&" + sessionFactoryBeanName, LocalSessionFactoryBean.class);
    } catch (NoSuchBeanDefinitionException e) {
        logger.error("Couldn't load hibernate session factory configuration bean", e);
        return;
    }
    SchemaExport schemaExport = new SchemaExport(sessionFactory.getConfiguration());
    schemaExport.setOutputFile(outputFileName).setDelimiter(";");
    schemaExport.execute(false, false, false, false);
}

From source file:net.ggtools.maven.ddlgenerator.DDLGenerator.java

License:Open Source License

public void createSchema() {
    log.info("Exporting DDL file to " + ddlFile);
    createDirectoriesIfNeeded();//from   w ww.  jav  a2 s .c om
    puManager.preparePersistenceUnitInfos();
    final PersistenceUnitInfo puInfo = puManager.obtainPersistenceUnitInfo(persistenceUnitName);
    final Ejb3Configuration ejb3Config = new Ejb3Configuration();
    ejb3Config.configure(puInfo, configProperties);
    final Field field = ReflectionUtils.findField(Ejb3Configuration.class, "cfg");
    ReflectionUtils.makeAccessible(field);
    final ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(configProperties)
            .buildServiceRegistry();
    final Configuration configuration = (Configuration) ReflectionUtils.getField(field, ejb3Config);
    final SchemaExport export = new SchemaExport(registry, configuration);
    export.setDelimiter(";"); // TODO introduce parameter
    export.setOutputFile(ddlFile.getAbsolutePath());
    export.execute(true, false, false, true);
}

From source file:net.leadware.hibernate4.maven.plugin.ShemaExportMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    // Un log//  w  w  w . j  av  a  2 s  .  c om
    getLog().info("Exportation de l'Unite de persistence: " + unitName + ".");

    // Initialisation du repertoire de sortie
    initOutputDirectory();

    // Fichier de drop
    File dropFile = new File(dropOutputFile.trim());

    // Fichier de drop
    File createFile = new File(createOutputFile.trim());

    // Fichier de drop
    File updateFile = null;

    // Obtention du Thread courant
    final Thread currentThread = Thread.currentThread();

    // Obtention du stream de sortie
    final PrintStream oldOut = System.out;

    // Obtention du classloader du thread en cours
    final ClassLoader oldClassLoader = currentThread.getContextClassLoader();

    try {

        // Positionnement de la sortie par defaut
        System.setOut(new PrintStream(new ByteArrayOutputStream()));

        // Positionnement du classloader avec ajout des chemins de classe du projet maven sous-jacent
        currentThread.setContextClassLoader(buildClassLoader(oldClassLoader));

        // Configuration EJB3
        Ejb3Configuration jpaConfiguration = null;

        // Si le fichier de persistence est renseigne
        if (persistenceFile != null && !persistenceFile.trim().isEmpty()) {

            // On positionne le fichier de persistence
            jpaConfiguration = new Ejb3Configuration().addFile(persistenceFile).configure(unitName, null);

        } else {

            // Configuration EJB3
            jpaConfiguration = new Ejb3Configuration().configure(unitName, null);
        }

        // Configuration Hibernate
        Configuration configuration = jpaConfiguration.getHibernateConfiguration();

        // Si le dialect a ete precise dans la configuration du plugin
        if (dialect != null && !dialect.trim().isEmpty())
            configuration.setProperty("hibernate.dialect", dialect.trim());

        // Exporteur de schema
        SchemaExport exporter = new SchemaExport(configuration);

        // Positionnement du delimiteur
        exporter.setDelimiter(delimiter);

        // Positionnement du fichier de sortie en drop
        exporter.setOutputFile(dropFile.getAbsolutePath());

        // Exportation des scripts drop
        exporter.execute(true, false, true, false);

        // Positionnement du fichier de sortie en create
        exporter.setOutputFile(createFile.getAbsolutePath());

        // Exportation des scripts drop
        exporter.execute(true, false, false, true);

        // Si le chemin des scripts de mise a jour est positionne
        if (updateOutputFile != null && !updateOutputFile.trim().isEmpty()) {

            // Modificateur de schema
            SchemaUpdate updater = new SchemaUpdate(configuration);

            // Fichier de drop
            updateFile = new File(updateOutputFile.trim());

            // Positionnement du fichier de sortie en create
            updater.setOutputFile(updateFile.getAbsolutePath());

            // Exportation des scripts drop
            updater.execute(true, true);
        }

        // Si il ya des cripts additionnels
        if (extendedScripts != null) {

            // Parcours de la liste des scripts de creation
            for (String script : extendedScripts.getCreateScripts()) {

                // Tentative de construction d'un File sur le la chaine script
                File scriptFile = new File(script);

                // Si l'objet existe et est un fichier
                if (scriptFile.exists() && scriptFile.isFile()) {

                    // Ajout de son contenu dans le fichier de script en cours
                    FileUtils.fileAppend(createFile.getAbsolutePath(), "\n\n" + FileUtils.fileRead(scriptFile));

                } else {

                    // Ajout du script dans le fichier
                    FileUtils.fileAppend(createFile.getAbsolutePath(), "\n\t" + script);
                }
            }

            // Parcours de la liste des scripts de suppression
            for (String script : extendedScripts.getDropScripts()) {

                // Tentative de construction d'un File sur le la chaine script
                File scriptFile = new File(script);

                // Si l'objet existe et est un fichier
                if (scriptFile.exists() && scriptFile.isFile()) {

                    // Ajout de son contenu dans le fichier de script en cours
                    FileUtils.fileAppend(dropFile.getAbsolutePath(), "\n\n" + FileUtils.fileRead(scriptFile));

                } else {

                    // Ajout du script dans le fichier
                    FileUtils.fileAppend(dropFile.getAbsolutePath(), "\n\t" + script);
                }
            }

            // Si le chemin des scripts de mise a jour est positionne
            if (updateOutputFile != null && !updateOutputFile.trim().isEmpty()) {

                // Parcours de la liste des scripts de mise a jour
                for (String script : extendedScripts.getUpdateScripts()) {

                    // Tentative de construction d'un File sur le la chaine script
                    File scriptFile = new File(script);

                    // Si l'objet existe et est un fichier
                    if (scriptFile.exists() && scriptFile.isFile()) {

                        // Ajout de son contenu dans le fichier de script en cours
                        FileUtils.fileAppend(updateFile.getAbsolutePath(),
                                "\n\n" + FileUtils.fileRead(scriptFile));

                    } else {

                        // Ajout du script dans le fichier
                        FileUtils.fileAppend(updateFile.getAbsolutePath(), "\n\t" + script);
                    }
                }

            }
        }

    } catch (Exception e) {

        // On relance
        throw new MojoExecutionException(e.getMessage(), e);

    } finally {

        // On repositionne la sortie standard
        System.setOut(oldOut);

        // On repositionne le classloader
        currentThread.setContextClassLoader(oldClassLoader);
    }
}

From source file:nl.strohalm.cyclos.setup.ExportScript.java

License:Open Source License

/**
 * Export the script for creating the database
 *//*from  ww  w.j  a va2 s.  co  m*/
public void run() {
    if (!exportTo.isAbsolute()) {
        exportTo = new File(SystemUtils.getUserDir(), exportTo.getPath());
    }
    // Resolve the file name
    if (exportTo.isDirectory()) {
        exportTo = new File(exportTo, "cyclos.ddl");
    }
    // Create the directory if needed
    final File dir = exportTo.getParentFile();
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new IllegalStateException("Could not create directory: " + dir);
        }
    }
    final String fileName = exportTo.getAbsolutePath();

    Setup.out.println(bundle.getString("export-script.start"));

    final SchemaExport schemaExport = new SchemaExport(configuration);
    schemaExport.setDelimiter(";");
    schemaExport.setOutputFile(fileName);
    schemaExport.create(true, false);

    Setup.out.println(bundle.getString("export-script.end") + " " + fileName);
}

From source file:org.ambraproject.hibernate.SchemaGenerator.java

License:Apache License

/**
 * Generate the sql for creating the schema
 *
 * @param dialect - Database dialect to use
 *///  w w  w. j  av a 2s  . c o  m
public void generateSQL(Dialect dialect) {
    configuration.setProperty("hibernate.dialect", dialect.getDialectClass());

    SchemaExport export = new SchemaExport(configuration);
    export.setDelimiter(";");
    String outputFile = this.outputDir + File.separator + "ddl_" + dialect.name().toLowerCase() + ".sql";
    export.setOutputFile(outputFile);
    export.execute(false, false, false, !updateSchema);
}

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  w  w  . j a va2 s  .com
 */
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);
    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 {/* w  w w  .java  2  s.c  o  m*/
        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 {//from  w  w  w  .  ja v  a  2s.  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
 *//*  ww  w. j  a  v  a  2 s .  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>");
            }
        }
    }
}