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:fr.mycellar.tools.DdlExport.java

License:Open Source License

public static void main(String... args) {
    org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
    cfg.addAnnotatedClass(Image.class);
    cfg.addAnnotatedClass(Address.class);
    cfg.addAnnotatedClass(Map.class);
    cfg.addAnnotatedClass(Position.class);
    cfg.addAnnotatedClass(IdentifiedEntity.class);
    cfg.addAnnotatedClass(NamedEntity.class);
    cfg.addAnnotatedClass(Bottle.class);
    cfg.addAnnotatedClass(Cellar.class);
    cfg.addAnnotatedClass(Input.class);
    cfg.addAnnotatedClass(Output.class);
    cfg.addAnnotatedClass(Stock.class);
    cfg.addAnnotatedClass(User.class);
    cfg.addAnnotatedClass(Appellation.class);
    cfg.addAnnotatedClass(Country.class);
    cfg.addAnnotatedClass(Format.class);
    cfg.addAnnotatedClass(Producer.class);
    cfg.addAnnotatedClass(Region.class);
    cfg.addAnnotatedClass(Varietal.class);
    cfg.addAnnotatedClass(Wine.class);
    cfg.addAnnotatedClass(Stack.class);
    cfg.addAnnotatedClass(CellarShare.class);
    cfg.addAnnotatedClass(Booking.class);
    cfg.addAnnotatedClass(BookingEvent.class);
    cfg.addAnnotatedClass(BookingBottle.class);
    cfg.addAnnotatedClass(Contact.class);
    cfg.addAnnotatedClass(Configuration.class);
    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setDelimiter(";");
    schemaExport.execute(true, false, false, true);
}

From source file:io.milton.cloud.server.db.utils.SchemaExporter.java

License:Open Source License

/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use/*from   w ww .j a  v  a  2s . 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 (String packageName : packageNames) {
        for (Class<Object> clazz : getClasses(packageName)) {
            cfg.addAnnotatedClass(clazz);
        }
    }
    List<File> outFiles = new ArrayList<>();
    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);
        outFiles.add(fOut);
    }
    System.out.println("**********************************");
    for (File f : outFiles) {
        System.out.println("   exported: " + f.getAbsolutePath());
    }
    System.out.println("**********************************");
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java

License:Open Source License

/**
 * Helper method to generate a schema creation SQL script from the given Hibernate
 * configuration.//from   w  w  w  . ja va 2 s.c  om
 */
private static void dumpSchemaCreate(Configuration cfg, File schemaOutputFile) {
    // if the file exists, delete it
    if (schemaOutputFile.exists()) {
        schemaOutputFile.delete();
    }
    SchemaExport schemaExport = new SchemaExport(cfg).setFormat(true).setHaltOnError(true)
            .setOutputFile(schemaOutputFile.getAbsolutePath()).setDelimiter(";");
    schemaExport.execute(false, false, false, true);
}

From source file:lucee.runtime.orm.hibernate.HibernateSessionFactory.java

License:Open Source License

private static void schemaExport(Log log, Configuration configuration, DatasourceConnection dc,
        SessionFactoryData data) throws PageException, SQLException, IOException {
    ORMConfiguration ormConf = data.getORMConfiguration();

    if (ORMConfiguration.DBCREATE_NONE == ormConf.getDbCreate()) {
        return;/*from  w ww.  j av a2s  .  c  o  m*/
    } else if (ORMConfiguration.DBCREATE_DROP_CREATE == ormConf.getDbCreate()) {
        SchemaExport export = new SchemaExport(configuration);
        export.setHaltOnError(true);

        export.execute(false, true, false, false);
        printError(log, data, export.getExceptions(), false);
        executeSQLScript(ormConf, dc);
    } else if (ORMConfiguration.DBCREATE_UPDATE == ormConf.getDbCreate()) {
        SchemaUpdate update = new SchemaUpdate(configuration);
        update.setHaltOnError(true);
        update.execute(false, true);
        printError(log, data, update.getExceptions(), false);
    }
}

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  v  a2s  .c o  m
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   ww w.j  a  va  2s  . 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//from   w ww. j  a v  a 2  s.  c  o  m
    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:net.sf.sail.webapp.DbSchemaExporter.java

License:Open Source License

/**
 * @param springConfigClassname/*ww w  . ja  v a 2s  .  c om*/
 * @param filename
 * @throws ClassNotFoundException
 * @throws FileNotFoundException
 */
public static void exportSchemaToFile(String springConfigClassname, String filename)
        throws ClassNotFoundException, FileNotFoundException {
    ConfigurableApplicationContext applicationContext = null;
    try {
        SpringConfiguration springConfig = (SpringConfiguration) BeanUtils
                .instantiateClass(Class.forName(springConfigClassname));
        applicationContext = new ClassPathXmlApplicationContext(
                springConfig.getRootApplicationContextConfigLocations());
        Configuration hibernateConfig = ((LocalSessionFactoryBean) applicationContext
                .getBean("&sessionFactory")).getConfiguration();

        final boolean printScriptToConsole = false, exportScriptToDb = false, justDrop = false,
                justCreate = true;
        final SchemaExport schemaExport = new SchemaExport(hibernateConfig).setDelimiter(";").setFormat(true)
                .setHaltOnError(true).setOutputFile(filename);
        schemaExport.execute(printScriptToConsole, exportScriptToDb, justDrop, justCreate);

    } finally {
        if (applicationContext != null) {
            applicationContext.close();
        }
    }
}

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

License:Apache License

/**
 * Generate the sql for creating the schema
 *
 * @param dialect - Database dialect to use
 *//*www  .j  a v  a  2 s .  c om*/
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.ambraproject.hibernate.SchemaGenerator.java

License:Apache License

/**
 * Run the schema creation script/*  w w  w.jav a  2s .  c o  m*/
 *
 * @param jdbcUrl  - the jdbc url for the database in which to run the script
 * @param dialect- the sql dialect for the database
 * @param username - the username for the database
 * @param password - the password to use
 */
public void createSchema(String jdbcUrl, Dialect dialect, String username, String password) {
    configuration.setProperty("connection.url", jdbcUrl);
    configuration.setProperty("connection.username", username);
    configuration.setProperty("connection.password", password);
    configuration.setProperty("dialect", dialect.getDialectClass());
    configuration.setProperty("connection.driver_class", dialect.getDriverClass());
    SchemaExport export = new SchemaExport(configuration);
    export.setDelimiter(";");
    export.execute(false, true, false, !updateSchema);
}