Example usage for org.hibernate.tool.hbm2ddl SchemaExport setFormat

List of usage examples for org.hibernate.tool.hbm2ddl SchemaExport setFormat

Introduction

In this page you can find the example usage for org.hibernate.tool.hbm2ddl SchemaExport setFormat.

Prototype

public SchemaExport setFormat(boolean format) 

Source Link

Document

Should we format the sql strings?

Usage

From source file:GenerateSchema.java

License:BSD License

/**
 * @param args/*w ww  . j av  a 2 s  . c om*/
 */
public static void main(String[] args) {

    Configuration cfg = new Configuration().configure();
    SchemaExport schemaExport = new SchemaExport(cfg);
    schemaExport.setFormat(true);
    schemaExport.setOutputFile("test.sql");
    schemaExport.create(true, false);
}

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 v a2s  .  c  o m*/
        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:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

private void traceDDL() {
    try {//ww  w. ja v 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.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/*from   w  w  w. ja  v  a2s  .  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// w w w  .  j  a v  a 2s .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);
}

From source file:com.github.antennaesdk.messageserver.db.H2.H2Database.java

License:Apache License

public void generateSchemaAndCreateTables(SimpleDriverDataSource dataSource) {

    // Get the tables that are already in the DATABASE
    List<String> tables = new ArrayList<>();
    try {/*from   w w w .ja v a 2  s .c  o  m*/
        Connection connection = dataSource.getConnection();
        DatabaseMetaData databaseMetadata = connection.getMetaData();
        ResultSet resultSet = databaseMetadata.getTables(null, null, null, new String[] { "TABLE" });
        while (resultSet.next()) {
            String table = resultSet.getString(3);
            logger.info("Table : " + table + " ... exists");
            tables.add(table);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // Get the tables that are needed from Entity Classes
    List<Class> tablesToCreate = new ArrayList<>();
    for (Class<?> c : entityClasses) {
        // get the table names
        Table table = c.getAnnotation(Table.class);

        logger.info("Entity: " + c.getName() + " , Table: " + table.name());
        boolean isExisting = false;
        for (String dbTable : tables) {
            if (dbTable.equals(table.name())) {
                isExisting = true;
                break;
            }
        }

        if (!isExisting) {
            // these tables must be created
            tablesToCreate.add(c);
        }
    }

    // Check whether the tables need to be created...
    if (tablesToCreate.size() == 0) {
        logger.info("Tables already exist... ");
        return;
    } else {
        logger.info("Creating tables...");
    }

    //create a minimal configuration
    org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    cfg.setProperty("hibernate.hbm2ddl.auto", "create");

    // create a temporary file to write the DDL
    File ddlFile = null;
    try {
        File dir = getDirectoryFromClasspath();
        ddlFile = File.createTempFile("H2_", ".SQL", dir);
        ddlFile.deleteOnExit();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // add the tables to be created
    for (Class c : tablesToCreate) {
        cfg.addAnnotatedClass(c);
    }

    //build all the mappings, before calling the AuditConfiguration
    cfg.buildMappings();
    cfg.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, ddlFile.getName());

    cfg.getProperties().setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    cfg.getProperties().setProperty("hibernate.connection.url", dataSource.getUrl());
    cfg.getProperties().setProperty("hibernate.connection.username", dataSource.getUsername());
    cfg.getProperties().setProperty("hibernate.connection.password", dataSource.getPassword());

    //execute the export
    SchemaExport export = new SchemaExport(cfg);

    export.setDelimiter(";");
    export.setFormat(true);
    // create the tables in the DB and show the DDL in console
    export.create(true, true);
}

From source file:com.github.gekoh.yagen.ddl.DDLGenerator.java

License:Apache License

public void writeDDL(Profile profile) {
    SchemaExport export = new SchemaExportFactory().createSchemaExport(profile);
    export.setDelimiter(";");
    export.setFormat(true);
    export.setOutputFile(profile.getOutputFile());
    export.execute(true, false, false, true);

    LOG.info("schema script written to file {}", profile.getOutputFile());
}

From source file:com.ikon.dao.HibernateUtil.java

License:Open Source License

/**
 * Generate database schema and initial data for a defined dialect
 *//*from w w  w . java2 s.c om*/
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);
}

From source file:com.imos.sample.service.HibernateService.java

/**
 * Hibernate configuration.//  ww  w. jav a2s  .co  m
 *
 * @throws RepositoryException
 */
public void config() throws RepositoryException {
    try {
        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        if (filePath == null || filePath.isEmpty()) {
            registryBuilder = registryBuilder.configure();
        } else {
            registryBuilder = registryBuilder.configure(filePath);
        }
        registry = registryBuilder.build();

        MetadataSources metaData = new MetadataSources(registry);
        sessionFactory = metaData.buildMetadata().buildSessionFactory();
        session = sessionFactory.openSession();

        SchemaExport schemaExport = new SchemaExport();
        schemaExport.setDelimiter(";");
        schemaExport.setFormat(true);
        schemaExport.setManageNamespaces(true);
        schemaExport.setOutputFile("./ddl_skilldb.sql");
        schemaExport.execute(EnumSet.of(TargetType.SCRIPT, TargetType.DATABASE, TargetType.STDOUT),
                SchemaExport.Action.CREATE, metaData.buildMetadata(registry), registry);

        log.info("Configuration succeed");
    } catch (HibernateException e) {
        StandardServiceRegistryBuilder.destroy(registry);
        log.error("Configuration failed : {}", e);
    }
}

From source file:com.oneandone.relesia.tools.SQLScriptGenerator.java

License:Apache License

public static void main(String[] args) throws MappingException, IOException {

    String createSQLFile = "dbscripts/createTables.sql";
    String dropSQLFile = "dbscripts/dropTables.sql";
    String hibernateCfgFile = "/db/hibernate.cfg.xml";

    final EnumSet<TargetType> targetTypes = EnumSet.noneOf(TargetType.class);
    targetTypes.add(TargetType.SCRIPT);//  w w  w  .j  ava2 s. co m

    System.out.println("Initialize Hibernate configuration from " + hibernateCfgFile);

    Configuration cfg = new Configuration().configure(hibernateCfgFile);
    Metadata metadata = MetadataHelper.getMetadata(cfg);

    SchemaExport export = new SchemaExport();
    export.setHaltOnError(true);
    export.setFormat(true);
    export.setDelimiter(";");

    System.out.println("Generating create SQL to file " + createSQLFile);
    if (new File(createSQLFile).exists()) {
        Files.delete(Paths.get(createSQLFile));
    }
    export.setOutputFile(createSQLFile);
    export.execute(targetTypes, Action.CREATE, metadata);

    System.out.println("Generating drop SQL to file " + dropSQLFile);
    export.setOutputFile(dropSQLFile);
    if (new File(dropSQLFile).exists()) {
        Files.delete(Paths.get(dropSQLFile));
    }
    export.execute(targetTypes, Action.DROP, metadata);

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