Java Code Examples for org.hibernate.tool.hbm2ddl.SchemaExport#execute()

The following examples show how to use org.hibernate.tool.hbm2ddl.SchemaExport#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: App.java    From juddi with Apache License 2.0 6 votes vote down vote up
/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use
 */
private void generate(Dialect dialect) {

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        ssrb.applySetting("hibernate.dialect", dialect.getDialectClass());
        StandardServiceRegistry standardServiceRegistry = ssrb.build();

        MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
        for (Class clzz : jpaClasses) {
                metadataSources.addAnnotatedClass(clzz);
        }

        Metadata metadata = metadataSources.buildMetadata();

        SchemaExport export = new SchemaExport();

        export.setDelimiter(";");
        export.setOutputFile(dialect.name().toLowerCase() + ".ddl");
        //export.execute(true, false, false, true);
        export.execute(EnumSet.of(TargetType.SCRIPT), Action.BOTH, metadata);
}
 
Example 2
Source File: SchemaGenerator.java    From core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Method that actually creates the file.
 * 
 * @param dbDialect to use
 */
private void generate(Dialect dialect) {
	cfg.setProperty("hibernate.dialect", dialect.getDialectClass());

	SchemaExport export = new SchemaExport(cfg);
	export.setDelimiter(";");
	
	// Determine file name. Use "ddl_" plus dialect name such as mysql or
	// oracle plus the package name with "_" replacing "." such as
	// org_transitime_db_structs .
	String packeNameSuffix = 
			packageName.replace(".", "_");
	String outputFilename = (outputDirectory!=null?outputDirectory+"/" : "") + 
			"ddl_" + dialect.name().toLowerCase() + 
			"_" + packeNameSuffix + ".sql";
	
	export.setOutputFile(outputFilename);
	
	// Export, but only to an SQL file. Don't actually modify the database
	System.out.println("Writing file " + outputFilename);
	export.execute(true, false, false, false);
	
	// Get rid of unneeded SQL for dropping tables and keys and such
	trimCruftFromFile(outputFilename);
}
 
Example 3
Source File: SchemaGenerator.java    From jpa2ddl with Apache License 2.0 4 votes vote down vote up
void generate(GeneratorSettings settings) throws Exception {
	validateSettings(settings);

	if (settings.getJpaProperties().getProperty(HIBERNATE_DIALECT) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
	}

	if (settings.isSkipSequences() && settings.getJpaProperties().getProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER, NoSequenceFilterProvider.class.getCanonicalName());
	}

	File outputFile = settings.getOutputPath();

	EngineDecorator engineDecorator = EngineDecorator.getEngineDecorator(settings.getJpaProperties().getProperty(HIBERNATE_DIALECT));

	if (settings.getGenerationMode() == GenerationMode.DATABASE) {

		String dbUrl = engineDecorator.decorateConnectionString(DB_URL);

		if (settings.getAction() == Action.UPDATE) {
			outputFile = FileResolver.resolveNextMigrationFile(settings.getOutputPath());
		}

		settings.getJpaProperties().setProperty("hibernate.connection.url", dbUrl);
		settings.getJpaProperties().setProperty("hibernate.connection.username", "sa");
		settings.getJpaProperties().setProperty("hibernate.connection.password", "");
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.action", settings.getAction().toSchemaGenerationAction());

		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.create-target", outputFile.getAbsolutePath());
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.drop-target", outputFile.getAbsolutePath());

		settings.getJpaProperties().setProperty("hibernate.hbm2ddl.delimiter", settings.getDelimiter());
		settings.getJpaProperties().setProperty("hibernate.format_sql", String.valueOf(settings.isFormatOutput()));
	}

	MetadataSources metadata = new MetadataSources(
			new StandardServiceRegistryBuilder()
					.applySettings(settings.getJpaProperties())
					.build());

	for (String packageName: settings.getPackages().stream().sorted().collect(Collectors.toList())) {
		FileResolver.listClassNamesInPackage(packageName).stream().sorted().forEach(metadata::addAnnotatedClassName);
		metadata.addPackage(packageName);
	}

	if (settings.getAction() != Action.UPDATE) {
		Files.deleteIfExists(settings.getOutputPath().toPath());
	}

	if (settings.getGenerationMode() == GenerationMode.METADATA) {
		SchemaExport export = new SchemaExport();
		export.setFormat(settings.isFormatOutput());
		export.setDelimiter(settings.getDelimiter());
		export.setOutputFile(outputFile.getAbsolutePath());
		export.execute(EnumSet.of(TargetType.SCRIPT), settings.getAction().toSchemaExportAction(), metadata.buildMetadata());
	} else {
		Connection connection = null;
		if (settings.getAction() == Action.UPDATE) {
			connection = DriverManager.getConnection(DB_URL, "SA", "");

			engineDecorator.decorateDatabaseInitialization(connection);

			List<Path> resolvedMigrations = FileResolver.resolveExistingMigrations(settings.getOutputPath(), false, true);
			for (Path resolvedMigration : resolvedMigrations) {
				String statement = new String(Files.readAllBytes(resolvedMigration));
				connection.prepareStatement(statement).execute();
			}
		}

		metadata.buildMetadata().buildSessionFactory().close();

		if (connection != null) {
			connection.close();
		}
	}

	if (outputFile.exists()) {
		if (outputFile.length() == 0) {
			Files.delete(outputFile.toPath());
		} else {
			List<String> lines = Files.readAllLines(outputFile.toPath())
					.stream()
					.map(line -> line.replaceAll("(?i)JPA2DDL\\.(PUBLIC\\.)?", ""))
					.collect(Collectors.toList());
			Files.write(outputFile.toPath(), lines);
		}
	}
}