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

The following examples show how to use org.hibernate.tool.hbm2ddl.SchemaExport#setDelimiter() . 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: DdlExporter.java    From sample-boot-micro with MIT License 6 votes vote down vote up
private void outputDdl(String packageName, String dialect, String fileName) {
    LocalSessionFactoryBean sfBean = sfBean(packageName, dialect);
    StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build();
    try {
        String outputFile = OutputRoot + fileName;
        Files.deleteIfExists(Paths.get(outputFile));
        Metadata metadata = metadata(serviceRegistry, sfBean.getMetadataSources());
        
        SchemaExport export = new SchemaExport();
        export.setDelimiter(";");
        export.setFormat(FormatSql);
        export.setOutputFile(outputFile);
        export.create(EnumSet.of(TargetType.SCRIPT, TargetType.STDOUT), metadata);
    } catch (Exception e) {
        throw new InvocationException(e);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
 
Example 2
Source File: HibernateUtil.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate database schema and initial data for a defined dialect
 */
public static void generateDatabase(String dialect) throws IOException {
	// Configure Hibernate
	log.info("Exporting Database Schema...");
	String dbSchema = EnvironmentDetector.getUserHome() + "/schema.sql";
	Configuration cfg = getConfiguration().configure();
	cfg.setProperty("hibernate.dialect", dialect);
	SchemaExport se = new SchemaExport(cfg);
	se.setOutputFile(dbSchema);
	se.setDelimiter(";");
	se.setFormat(false);
	se.create(false, false);
	log.info("Database Schema exported to {}", dbSchema);

	String initialData = new File("").getAbsolutePath() + "/src/main/resources/default.sql";
	log.info("Exporting Initial Data from '{}'...", initialData);
	String initData = EnvironmentDetector.getUserHome() + "/data.sql";
	FileInputStream fis = new FileInputStream(initialData);
	String ret = DatabaseDialectAdapter.dialectAdapter(fis, dialect);
	FileWriter fw = new FileWriter(initData);
	IOUtils.write(ret, fw);
	fw.flush();
	fw.close();
	log.info("Initial Data exported to {}", initData);
}
 
Example 3
Source File: Test.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Only for testing purposes
 */
public static void main(String[] args) throws Exception {
	log.info("Generate database schema & initial data");
	HibernateUtil.generateDatabase("org.hibernate.dialect.Oracle10gDialect");
	Configuration cfg = new Configuration();

	// Add annotated beans
	cfg.addAnnotatedClass(NodeFolder.class);

	// Configure Hibernate
	cfg.setProperty("hibernate.dialect", Config.HIBERNATE_DIALECT);
	cfg.setProperty("hibernate.hbm2ddl.auto", "create");

	SchemaExport se = new SchemaExport(cfg);
	se.setOutputFile("/home/pavila/export.sql");
	se.setDelimiter(";");
	se.setFormat(false);
	se.create(false, false);
}
 
Example 4
Source File: DdlExporter.java    From sample-boot-hibernate with MIT License 6 votes vote down vote up
private void outputDdl(String packageName, String dialect, String fileName) {
    LocalSessionFactoryBean sfBean = sfBean(packageName, dialect);
    StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build();
    try {
        String outputFile = OutputRoot + fileName;
        Files.deleteIfExists(Paths.get(outputFile));
        Metadata metadata = metadata(serviceRegistry, sfBean.getMetadataSources());
        
        SchemaExport export = new SchemaExport();
        export.setDelimiter(";");
        export.setFormat(FormatSql);
        export.setOutputFile(outputFile);
        export.create(EnumSet.of(TargetType.SCRIPT, TargetType.STDOUT), metadata);
    } catch (Exception e) {
        throw new InvocationException(e);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
 
Example 5
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 6
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 7
Source File: DatabaseSetup.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Write database configuration to file. Includes differences to existing database. Filename: "database/setupDatabase.sql"
 */
private static void exportDDLtoFile() {
    String outputFile = "database/setupDatabase.sql";

    boolean script = true; // write DDL
    boolean export = false; // don't update databse
    try {
        SchemaExport se = new SchemaExport(cf);
        se.setOutputFile(outputFile);
        se.setDelimiter(";");
        se.create(script, export);
    } catch (Exception e) {
        log.error("DDL export to file failed: Reason: ", e);
    }
}
 
Example 8
Source File: DatabaseSetup.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Write database configuration to file. Includes differences to existing database. Filename: "database/setupDatabase.sql"
 */
private static void exportDDLtoFile() {
    String outputFile = "database/setupDatabase.sql";

    boolean script = true; // write DDL
    boolean export = false; // don't update databse
    try {
        SchemaExport se = new SchemaExport(cf);
        se.setOutputFile(outputFile);
        se.setDelimiter(";");
        se.create(script, export);
    } catch (Exception e) {
        log.error("DDL export to file failed: Reason: ", e);
    }
}
 
Example 9
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);
		}
	}
}