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:com.yahoo.elide.datastores.hibernate3.HibernateDataStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // Add additional checks to our static check mappings map.
    // NOTE: This is a bit hacky. We need to do a major overhaul on our test architecture
    TestCheckMappings.MAPPINGS.put("filterCheck", Filtered.FilterCheck.class);
    TestCheckMappings.MAPPINGS.put("filterCheck3", Filtered.FilterCheck3.class);

    // method to force class initialization
    Configuration configuration = new Configuration();
    try {// w w  w .  j  a  v  a 2 s  . com
        ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class)
                .forEach(configuration::addAnnotatedClass);
    } catch (MappingException e) {
        throw new RuntimeException(e);
    }

    SessionFactory sessionFactory = configuration.configure("hibernate.cfg.xml")
            .setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .setProperty(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306")
                            + "/root?serverTimezone=UTC")
            .setProperty(Environment.USER, "root").setProperty(Environment.PASS, "root").buildSessionFactory();

    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport(configuration).setHaltOnError(true);
    schemaExport.drop(false, true);
    schemaExport.execute(false, true, false, true);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException(schemaExport.getExceptions().toString());
    }

    return new HibernateStore(sessionFactory, true, ScrollMode.FORWARD_ONLY);
}

From source file:com.yahoo.elide.datastores.hibernate5.HibernateDataStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // Add additional checks to our static check mappings map.
    // NOTE: This is a bit hacky. We need to do a major overhaul on our test architecture
    TestCheckMappings.MAPPINGS.put("filterCheck", Filtered.FilterCheck.class);
    TestCheckMappings.MAPPINGS.put("filterCheck3", Filtered.FilterCheck3.class);

    // method to force class initialization
    MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").applySetting(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .applySetting(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306")
                            + "/root?serverTimezone=UTC")
            .applySetting(Environment.USER, "root").applySetting(Environment.PASS, "root").build());

    try {//from   ww  w . j a  v  a  2 s.c  o m
        ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class)
                .forEach(metadataSources::addAnnotatedClass);
    } catch (MappingException e) {
        throw new RuntimeException(e);
    }

    MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata();

    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport(metadataImplementor); //.setHaltOnError(true);
    schemaExport.drop(false, true);
    schemaExport.execute(false, true, false, true);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException(schemaExport.getExceptions().toString());
    }

    return new HibernateStore(metadataImplementor.buildSessionFactory(), true, ScrollMode.FORWARD_ONLY);
}

From source file:com.yahoo.elide.datastores.multiplex.bridgeable.BridgeableStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // method to force class initialization
    MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").applySetting(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .applySetting(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306")
                            + "/root?serverTimezone=UTC")
            .applySetting(Environment.USER, "root").applySetting(Environment.PASS, "root").build());

    metadataSources.addAnnotatedClass(HibernateUser.class);

    MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata();

    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport(metadataImplementor); //.setHaltOnError(true);
    schemaExport.drop(false, true);/*from  w  ww.  j av  a  2  s.  c o m*/
    schemaExport.execute(false, true, false, true);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException(schemaExport.getExceptions().toString());
    }

    LATEST_HIBERNATE_STORE = new HibernateStore.Builder(metadataImplementor.buildSessionFactory())
            .withScrollEnabled(true).withScrollMode(ScrollMode.FORWARD_ONLY).build();

    BridgeableRedisStore hbaseStore = new BridgeableRedisStore();

    return new MultiplexManager(LATEST_HIBERNATE_STORE, hbaseStore);
}

From source file:com.yahoo.elide.hibernate.AHibernateTest.java

License:Apache License

protected static void databaseManagerInit() {
    // method to force class initialization
    Configuration c = new Configuration();
    try {// w  w w  .  j av a2 s . co m
        ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class).forEach(c::addAnnotatedClass);
    } catch (MappingException e) {
        throw new RuntimeException(e);
    }
    sessionFactory = c.configure("hibernate.cfg.xml")
            .setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .setProperty(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306") + "/root")
            .setProperty(Environment.USER, "root").setProperty(Environment.PASS, "root").buildSessionFactory();

    // create Example tables from beans
    SchemaExport se = new SchemaExport(c).setHaltOnError(true);
    se.drop(false, true);
    se.execute(false, true, false, true);

    if (se.getExceptions().size() != 0) {
        throw new RuntimeException("" + se.getExceptions());
    }

    hibernateManager = new HibernateManager(sessionFactory);
}

From source file:com.zeroone.guestebook.domain.SchemaGenerator.java

License:Apache License

/**
 * Method that actually creates the file.
 *
 * @return the generated {@link File}./*  www . ja  v  a  2s  .c o m*/
 */
public File generate(File directory) {
    SchemaExport export = new SchemaExport(metadata);
    export.setDelimiter(";");
    File file = new File(directory, String.format("ddl_%s.sql", dialect.name().toLowerCase()));
    export.setOutputFile(file.getAbsolutePath());
    export.setFormat(true);
    export.execute(true, false, false, false);
    return file;
}

From source file:csns.util.Hbm2ddl.java

License:Open Source License

public static void main(String args[]) {
    if (args.length == 0) {
        System.err.println("java Hbm2ddl <outputFile>");
        return;/*from w  w  w  .  ja v a  2s  .  c  o m*/
    }

    System.out.print("Export DDL to " + args[0] + " ... ");

    Configuration cfg = (new Ejb3Configuration()).configure("csns2", new HashMap<String, Object>())
            .getHibernateConfiguration();

    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setOutputFile(args[0]).setDelimiter(";").setFormat(true).setHaltOnError(true);

    // . output script to console (and file if outputFile is set): true
    // . export to database: false
    // . only drop the tables: false
    // . only create the tables: true
    schemaExport.execute(true, false, false, true);

    System.out.println("Done.");
}

From source file:de.jpdigital.maven.plugins.hibernate4ddl.GenerateDdlMojo.java

License:Open Source License

/**
 * Helper method for generating the DDL classes for a specific dialect. This
 * is place for the real work is done. The method first creates an instance
 * of the {@link Configuration} class from Hibernate an puts the appropriate
 * values into it. It then creates an instance of the {@link SchemaExport}
 * class from the Hibernate API, configured this class, for example by
 * setting {@code format} to {@code true} so that the generated SQL files
 * are formatted nicely. After that it calls the
 * {@link SchemaExport#execute(boolean, boolean, boolean, boolean)} method
 * which will create the SQL script file. The method is called in a way
 * which requires <em>no</em> database connection.
 *
 *
 * @param dialect       The dialect for which the DDL files is generated.
 * @param entityClasses The entity classes for which the DDL file is
 *                      generated.//from   w ww  . j av  a2 s .  co m
 *
 * @throws MojoFailureException if something goes wrong.
 */
private void generateDdl(final Dialect dialect, final Set<Class<?>> entityClasses) throws MojoFailureException {
    final Configuration configuration = new Configuration();

    processPersistenceXml(configuration);

    configuration.setProperty("hibernate.hbm2ddl.auto", "create");

    for (final Class<?> entityClass : entityClasses) {
        configuration.addAnnotatedClass(entityClass);
    }

    configuration.setProperty("hibernate.dialect", dialect.getDialectClass());

    final SchemaExport export;
    if (useEnvers) {
        export = new EnversSchemaGenerator(configuration).export();
    } else {
        export = new SchemaExport(configuration);

    }
    export.setDelimiter(";");

    final Path tmpDir;
    try {
        tmpDir = Files.createTempDirectory("maven-hibernate-ddl-plugin");
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to create work dir.", ex);
    }
    export.setOutputFile(
            String.format("%s/%s.sql", tmpDir.toString(), dialect.name().toLowerCase(Locale.ENGLISH)));
    export.setFormat(true);
    export.execute(true, false, false, true);

    writeOutputFile(dialect, tmpDir);
}

From source file:de.tuclausthal.submissioninterface.util.HibernateSQLExporter.java

License:Open Source License

public static void main(String[] fdf) {
    SchemaExport bla = new SchemaExport(new AnnotationConfiguration().configure());
    bla.setOutputFile("1.sql");
    bla.execute(false, false, false, false);
}

From source file:edu.csula.squirrels.util.Hbm2ddl.java

License:Open Source License

public static void main(String args[]) {
    if (args.length == 0) {
        System.err.println("java Hbm2ddl <outputFile>");
        return;/*from  w ww. j av a 2 s .  c o m*/
    }

    System.out.print("Export DDL to " + args[0] + " ... ");

    Configuration cfg = (new Ejb3Configuration()).configure("squirrels", new HashMap<String, Object>())
            .getHibernateConfiguration();

    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setOutputFile(args[0]).setDelimiter(";").setFormat(true).setHaltOnError(true);

    // . output script to console (and file if outputFile is set): true
    // . export to database: false
    // . only drop the tables: false
    // . only create the tables: true
    schemaExport.execute(true, false, false, true);

    System.out.println("Done.");
}

From source file:edu.ku.brc.specify.tools.SpecifySchemaGenerator.java

License:Open Source License

/**
 * Creates the Schema.//from   w w  w. ja  v  a2  s. c  o m
 * @param driverInfo the driver info to use
 * @param connectionStr the connection string for creating or opening a database
 * @param hostname the hostname (localhost)
 * @param databaseName the database name
 * @param user the username
 * @param passwd the password (clear text)
 * @param doUpdate tells it to update the schema instead of creating it
 */
protected static void doGenSchema(final DatabaseDriverInfo driverInfo, final String connectionStr, // might be a create or an open connection string
        final String user, final String passwd, final boolean doUpdate) {
    // setup the Hibernate configuration
    Configuration hibCfg = new AnnotationConfiguration();
    hibCfg.setProperties(getHibernateProperties(driverInfo, connectionStr, user, passwd, doUpdate));
    hibCfg.configure();

    if (doUpdate) {
        SchemaUpdate schemaUpdater = new SchemaUpdate(hibCfg);

        log.info("Updating schema");
        //System.exit(0);
        boolean doScript = false;
        log.info("Updating the DB schema");
        schemaUpdater.execute(doScript, true);

        log.info("DB schema Updating completed");

        // log the exceptions that occurred
        List<?> exceptions = schemaUpdater.getExceptions();
        for (Object o : exceptions) {
            Exception e = (Exception) o;
            log.error(e.getMessage());
        }
    } else {
        SchemaExport schemaExporter = new SchemaExport(hibCfg);
        schemaExporter.setDelimiter(";");

        log.info("Generating schema");
        //System.exit(0);
        boolean printToScreen = false;
        boolean exportToDb = true;
        boolean justDrop = false;
        boolean justCreate = true;
        log.info("Creating the DB schema");
        schemaExporter.execute(printToScreen, exportToDb, justDrop, justCreate);

        log.info("DB schema creation completed");

        // log the exceptions that occurred
        List<?> exceptions = schemaExporter.getExceptions();
        for (Object o : exceptions) {
            Exception e = (Exception) o;
            log.error(e.getMessage());
        }
    }
}