List of usage examples for org.hibernate.tool.hbm2ddl SchemaExport execute
@SuppressWarnings("unchecked") public void execute(EnumSet<TargetType> targetTypes, Action action, Metadata metadata, ServiceRegistry serviceRegistry)
From source file:at.stefanproell.PersistentIdentifierMockup.HibernateSchemaGeneratorPID.java
License:Apache License
public static void main(String[] args) { String outputFilePath = "PersistentIdentification/additional_configuration/PID-Hibernate-schema.sql"; Configuration config = new Configuration(); config.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); config.addAnnotatedClass(PersistentIdentifier.class); config.addAnnotatedClass(Organization.class); SchemaExport export = new EnversSchemaGenerator(config).export().setOutputFile(outputFilePath); export.setDelimiter(";"); export.execute(true, false, false, false); // Update Schema //updateSchema(config); }
From source file:be.fedict.eid.applet.maven.sql.ddl.SQLDDLMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("SQL DDL script generator"); File outputFile = new File(this.outputDirectory, this.outputName); getLog().info("Output SQL DDL script file: " + outputFile.getAbsolutePath()); this.outputDirectory.mkdirs(); try {/*from w ww . j a va 2 s . c om*/ outputFile.createNewFile(); } catch (IOException e) { throw new MojoExecutionException("I/O error.", e); } for (ArtifactItem artifactItem : this.artifactItems) { getLog().info("artifact: " + artifactItem.getGroupId() + ":" + artifactItem.getArtifactId()); List<Dependency> dependencies = this.project.getDependencies(); String version = null; for (Dependency dependency : dependencies) { if (StringUtils.equals(dependency.getArtifactId(), artifactItem.getArtifactId()) && StringUtils.equals(dependency.getGroupId(), artifactItem.getGroupId())) { version = dependency.getVersion(); break; } } getLog().info("artifact version: " + version); VersionRange versionRange = VersionRange.createFromVersion(version); Artifact artifact = this.artifactFactory.createDependencyArtifact(artifactItem.getGroupId(), artifactItem.getArtifactId(), versionRange, "jar", null, Artifact.SCOPE_COMPILE); try { this.resolver.resolve(artifact, this.remoteRepos, this.local); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Unable to resolve artifact.", e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("Unable to find artifact.", e); } getLog().info("artifact file: " + artifact.getFile().getAbsolutePath()); getLog().info("hibernate dialect: " + this.hibernateDialect); URL artifactUrl; try { artifactUrl = artifact.getFile().toURI().toURL(); } catch (MalformedURLException e) { throw new MojoExecutionException("URL error.", e); } URLClassLoader classLoader = new URLClassLoader(new URL[] { artifactUrl }, this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(classLoader); AnnotationDB annotationDb = new AnnotationDB(); try { annotationDb.scanArchives(artifactUrl); } catch (IOException e) { throw new MojoExecutionException("I/O error.", e); } Set<String> classNames = annotationDb.getAnnotationIndex().get(Entity.class.getName()); getLog().info("# JPA entity classes: " + classNames.size()); AnnotationConfiguration configuration = new AnnotationConfiguration(); configuration.setProperty("hibernate.dialect", this.hibernateDialect); Dialect dialect = Dialect.getDialect(configuration.getProperties()); getLog().info("dialect: " + dialect.toString()); for (String className : classNames) { getLog().info("JPA entity: " + className); Class<?> entityClass; try { entityClass = classLoader.loadClass(className); getLog().info("entity class loader: " + entityClass.getClassLoader()); } catch (ClassNotFoundException e) { throw new MojoExecutionException("class not found.", e); } configuration.addAnnotatedClass(entityClass); } SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.setFormat(true); schemaExport.setHaltOnError(true); schemaExport.setOutputFile(outputFile.getAbsolutePath()); schemaExport.setDelimiter(";"); try { getLog().info("SQL DDL script: " + IOUtil.toString(new FileInputStream(outputFile))); } catch (FileNotFoundException e) { throw new MojoExecutionException("file not found.", e); } catch (IOException e) { throw new MojoExecutionException("I/O error.", e); } // operate schemaExport.execute(true, false, false, true); List<Exception> exceptions = schemaExport.getExceptions(); for (Exception exception : exceptions) { getLog().error("exception: " + exception.getMessage()); } } }
From source file:be.fedict.eid.pkira.blm.hibernateutil.SchemaGenerator.java
License:Open Source License
/** * Method that actually creates the file. * /*from w w w . ja va 2 s . c om*/ * @param dbDialect * to use */ private void generate(Dialect dialect) { new java.io.File(workingDir + "/schema").mkdirs(); cfg.setProperty("hibernate.dialect", dialect.getDialectClass()); SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setOutputFile(workingDir + "/schema/ddl_" + dialect.name().toLowerCase() + ".sql"); export.execute(true, false, false, false); }
From source file:bookpub.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 . j a v a2 s .co m } System.out.print("Export DDL to " + args[0] + " ... "); Configuration cfg = (new Ejb3Configuration()).configure("bookpub", 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:ca.mcgill.cs.swevo.qualyzer.model.PersistenceManager.java
License:Open Source License
/** * //from www.j a v a 2s . co m * Creates the HSQLDB database in the .db folder of project. * * @param project */ public void initDB(IProject project) { setupDBFolder(project); String dbPath = getDBPath(project).toOSString(); String connectionString = DB_CONNECTION_STRING.replace(PER_S, dbPath) + DB_INIT_STRING; //$NON-NLS-1$ HibernateDBManager dbManager; dbManager = new HibernateDBManager(connectionString, DB_USERNAME, "", DB_DRIVER, DB_DIALECT); //$NON-NLS-1$ // Add DB Manager fActivator.getHibernateDBManagers().put(project.getName(), dbManager); // Init DB SchemaExport export = new SchemaExport(dbManager.getConfiguration()); export.execute(false, true, false, false); }
From source file:com.amalto.core.storage.hibernate.HibernateStorage.java
License:Open Source License
private void traceDDL() { try {// w w w.j av a2 s.c o m if (configuration == null) { throw new IllegalStateException("Expect a Hibernate configuration to be set."); //$NON-NLS-1$ } String jbossServerTempDir = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$ RDBMSDataSource.DataSourceDialect dialectType = dataSource.getDialectName(); SchemaExport export = new SchemaExport(configuration); export.setFormat(false); String filename = jbossServerTempDir + File.separator + storageName + "_" + storageType + "_" //$NON-NLS-1$//$NON-NLS-2$ + dialectType + ".ddl"; //$NON-NLS-1$ export.setOutputFile(filename); export.setDelimiter(";"); //$NON-NLS-1$ export.execute(false, false, false, true); if (export.getExceptions().size() > 0) { for (int i = 0; i < export.getExceptions().size(); i++) { LOGGER.error("Error occurred while producing ddl.", //$NON-NLS-1$ (Exception) export.getExceptions().get(i)); } } LOGGER.info("DDL exported to file '" + filename + "'."); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { LOGGER.error("Error occurred while producing ddl.", e); //$NON-NLS-1$ } }
From source file:com.comcast.cats.recorder.persistence.SqlTableCreator.java
License:Open Source License
/** * Method that actually creates the file. * //w w w . j a v a2s . com * @param dbDialect * to use */ private void generate(Dialect dialect) { cfg.setProperty("hibernate.dialect", dialect.getDialectClass()); SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setOutputFile("ddl_" + dialect.name().toLowerCase() + ".sql"); export.execute(true, false, false, false); }
From source file:com.evolveum.midpoint.repo.sql.SpringApplicationContextTest.java
License:Apache License
private void createSQLSchema(String fileName, String dialect) throws Exception { org.hibernate.cfg.Configuration configuration = new Configuration(); configuration.setNamingStrategy(new MidPointNamingStrategy()); configuration.setProperties(sessionFactory.getHibernateProperties()); sessionFactory.getHibernateProperties().setProperty("hibernate.dialect", dialect); System.out.println("Dialect: " + sessionFactory.getHibernateProperties().getProperty("hibernate.dialect")); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.container", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.any", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.embedded", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.enums", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.id", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.other", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.type", configuration); addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.audit", configuration); // addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.poc", configuration); configuration.addPackage("com.evolveum.midpoint.repo.sql.type"); SchemaExport export = new SchemaExport(configuration); export.setOutputFile(fileName);/* www.j a v a 2 s. c o m*/ export.setDelimiter(";"); export.execute(true, false, false, true); }
From source file:com.foilen.smalltools.tools.Hibernate4Tools.java
License:Open Source License
/** * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)} * * @param dialect// w w w . j a va2 s.c o m * the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect ) * @param outputSqlFile * where to put the generated SQL file * @param useUnderscore * true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager" * @param packagesToScan * the packages where your entities are */ @SuppressWarnings("deprecation") public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile, boolean useUnderscore, String... packagesToScan) { // Configuration Configuration configuration = new Configuration(); if (useUnderscore) { configuration.setNamingStrategy(new ImprovedNamingStrategy()); } Properties properties = new Properties(); properties.setProperty(AvailableSettings.DIALECT, dialect.getName()); // Scan packages Set<String> classNames = new TreeSet<String>(); Set<String> packageNames = new TreeSet<String>(); try { for (String pkg : packagesToScan) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN; Resource[] resources = resourcePatternResolver.getResources(pattern); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); if (matchesEntityTypeFilter(reader, readerFactory)) { classNames.add(className); } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) { packageNames .add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length())); } } } } } catch (IOException ex) { throw new MappingException("Failed to scan classpath for unlisted classes", ex); } try { for (String className : classNames) { configuration.addAnnotatedClass(resourcePatternResolver.getClassLoader().loadClass(className)); } for (String packageName : packageNames) { configuration.addPackage(packageName); } } catch (ClassNotFoundException ex) { throw new MappingException("Failed to load annotated classes from classpath", ex); } // Exportation SchemaExport schemaExport = new SchemaExport(configuration, properties); schemaExport.setOutputFile(outputSqlFile); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); schemaExport.execute(true, false, false, true); }
From source file:com.foilen.smalltools.tools.Hibernate50Tools.java
License:Open Source License
/** * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)} * * @param dialect//from w ww. ja v a2 s .c o m * the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect ) * @param outputSqlFile * where to put the generated SQL file * @param useUnderscore * true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager" * @param packagesToScan * the packages where your entities are */ public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile, boolean useUnderscore, String... packagesToScan) { BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().build(); MetadataSources metadataSources = new MetadataSources(bootstrapServiceRegistry); ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false); scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class)); scanner.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class)); scanner.addIncludeFilter(new AnnotationTypeFilter(MappedSuperclass.class)); for (String pkg : packagesToScan) { for (BeanDefinition beanDefinition : scanner.findCandidateComponents(pkg)) { metadataSources.addAnnotatedClassName(beanDefinition.getBeanClassName()); } } StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry); standardServiceRegistryBuilder.applySetting(AvailableSettings.DIALECT, dialect.getName()); StandardServiceRegistryImpl ssr = (StandardServiceRegistryImpl) standardServiceRegistryBuilder.build(); MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(ssr); if (useUnderscore) { metadataBuilder.applyImplicitNamingStrategy(new SpringImplicitNamingStrategy()); metadataBuilder.applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy()); } MetadataImpl metadata = (MetadataImpl) metadataBuilder.build(); // Exportation SchemaExport schemaExport = new SchemaExport(metadata); schemaExport.setOutputFile(outputSqlFile); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); schemaExport.execute(true, false, false, true); }