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

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

Introduction

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

Prototype

public SchemaExport setHaltOnError(boolean haltOnError) 

Source Link

Document

Should we stop once an error occurs?

Usage

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 www .j av a 2 s. com
        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.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);/*from  w w w  . ja v  a2 s  .c  om*/

    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!");
}

From source file:lucee.runtime.orm.hibernate.HibernateSessionFactory.java

License:Open Source License

private static void schemaExport(Log log, Configuration configuration, DatasourceConnection dc,
        SessionFactoryData data) throws PageException, SQLException, IOException {
    ORMConfiguration ormConf = data.getORMConfiguration();

    if (ORMConfiguration.DBCREATE_NONE == ormConf.getDbCreate()) {
        return;//from   ww w  .  j  a va 2s.com
    } else if (ORMConfiguration.DBCREATE_DROP_CREATE == ormConf.getDbCreate()) {
        SchemaExport export = new SchemaExport(configuration);
        export.setHaltOnError(true);

        export.execute(false, true, false, false);
        printError(log, data, export.getExceptions(), false);
        executeSQLScript(ormConf, dc);
    } else if (ORMConfiguration.DBCREATE_UPDATE == ormConf.getDbCreate()) {
        SchemaUpdate update = new SchemaUpdate(configuration);
        update.setHaltOnError(true);
        update.execute(false, true);
        printError(log, data, update.getExceptions(), false);
    }
}

From source file:org.bedework.calcore.hibernate.SchemaBuilderImpl.java

License:Apache License

@Override
public void execute(final Properties props, final String outputFile, final boolean export,
        final String delimiter) throws CalFacadeException {
    try {//ww w.j a va2  s  . co m
        SchemaExport se = new SchemaExport(getConfiguration(props));

        if (delimiter != null) {
            se.setDelimiter(delimiter);
        }

        se.setFormat(true);
        se.setHaltOnError(false);
        se.setOutputFile(outputFile);

        se.execute(false, // script - causes write to System.out if true
                export, false, // drop
                true); // create
    } catch (Throwable t) {
        throw new CalFacadeException(t);
    }
}

From source file:org.bedework.synch.service.Synch.java

License:Apache License

@Override
public String schema() {
    String result = "Export complete: check logs";

    try {//  ww  w  . ja  v a 2 s . c om
        SchemaExport se = new SchemaExport(getConfiguration());

        if (getDelimiter() != null) {
            se.setDelimiter(getDelimiter());
        }

        se.setFormat(getFormat());
        se.setHaltOnError(getHaltOnError());
        se.setOutputFile(getSchemaOutFile());
        se.setImportFile(getSqlIn());

        se.execute(false, // script - causes write to System.out if true
                getExport(), getDrop(), getCreate());
    } catch (Throwable t) {
        error(t);
        result = "Exception: " + t.getLocalizedMessage();
    } finally {
        create = false;
        drop = false;
        export = false;
    }

    return result;
}

From source file:org.codehaus.mojo.hibernate3.exporter.Hbm2DDLExporterMojo.java

License:Apache License

/**
 * Overrides the default implementation of executing this goal.
 *
 * @throws MojoExecutionException if there is an error executing the goal
 *///ww  w.  j  av  a  2  s . c  o  m
protected void doExecute() throws MojoExecutionException {
    boolean scriptToConsole = getComponentProperty("console", true);
    boolean exportToDatabase = getComponentProperty("export", true);
    boolean haltOnError = getComponentProperty("haltonerror", false);
    boolean drop = getComponentProperty("drop", false);
    boolean create = getComponentProperty("create", true);
    String implementation = getComponentProperty("implementation", getComponent().getImplementation());

    Configuration configuration = getComponentConfiguration(implementation).getConfiguration(this);

    if (getComponentProperty("update", false)) {
        SchemaUpdate update = new SchemaUpdate(configuration);
        update.execute(scriptToConsole, exportToDatabase);
    } else {
        SchemaExport export = new SchemaExport(configuration);
        export.setDelimiter(getComponentProperty("delimiter", ";"));
        export.setHaltOnError(haltOnError);
        export.setFormat(getComponentProperty("format", false));

        String outputFilename = getComponentProperty("outputfilename");
        if (outputFilename != null) {
            File outputFile = HibernateUtils.prepareFile(
                    new File(getProject().getBasedir(), getComponent().getOutputDirectory()), outputFilename,
                    "outputfilename");
            export.setOutputFile(outputFile.toString());
        }

        if (drop && create) {
            export.create(scriptToConsole, exportToDatabase);
        } else {
            export.execute(scriptToConsole, exportToDatabase, drop, create);
        }

        if (export.getExceptions().size() > 0) {
            Iterator iterator = export.getExceptions().iterator();
            int cnt = 1;
            getLog().warn(export.getExceptions().size() + " errors occurred while performing <hbm2ddl>.");
            while (iterator.hasNext()) {
                getLog().error("Error #" + cnt + ": " + iterator.next().toString());
            }
            if (haltOnError) {
                throw new MojoExecutionException("Errors while performing <hbm2ddl>");
            }
        }
    }
}

From source file:org.jboss.bpm.monitor.model.hibernate.SchemaGenerator.java

License:Apache License

/**
 * Method that actually creates the file.
 *///w  w  w  . j a  va2 s. c  o  m
private void generate(Dialect dialect) {
    String s = output.getAbsolutePath() + "/ddl_" + dialect.name().toLowerCase() + ".sql";
    cfg.setProperty("hibernate.dialect", dialect.getDialectClass());

    SchemaExport export = new SchemaExport(cfg);
    export.setDelimiter(";");
    export.setOutputFile(s);
    export.setFormat(true);
    export.setHaltOnError(true);
    export.execute(true, false, false, false);

    System.out.println("==================");
    System.out.println("DDL: " + s);
    System.out.println("==================");
}

From source file:org.thelq.stackexchange.dbimport.DatabaseWriter.java

License:Apache License

public static void createTables(DumpContainer container) {
    SchemaExport exporter = new SchemaExport(container.getServiceRegistry(),
            container.getHibernateConfiguration());
    exporter.setHaltOnError(true);
    exporter.create(false, true);/* www .j ava 2s .  c  o m*/
    log.info("Finished creating tables for " + Utils.getLongLocation(container));
}