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

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

Introduction

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

Prototype

public void create(EnumSet<TargetType> targetTypes, Metadata metadata) 

Source Link

Usage

From source file:org.kuali.mobility.shared.controllers.HomeController.java

License:Open Source License

/**
 * Controller method to download a ddl.//w  w w  .j a  v a2  s.  com
 */
@Deprecated
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "ddl", method = RequestMethod.GET)
public void exportDatabaseSchema(HttpServletRequest request, HttpServletResponse response, Model uiModel) {
    PersistenceUnitInfo persistenceUnitInfo = getEntityManagerFactory().getPersistenceUnitInfo();

    Map jpaPropertyMap = getEntityManagerFactory().getJpaPropertyMap();
    jpaPropertyMap.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
            .getHibernateConfiguration();

    SchemaExport schema = new SchemaExport(configuration);
    schema.setFormat(true);
    schema.setDelimiter(";");
    schema.setOutputFile("/tmp/schema.sql");
    schema.create(false, false);
}

From source file:org.light.portal.core.dao.hibernate.PortalDaoImpl.java

License:Apache License

public void init(Portlets portlets, PortalLayout portalLayout, PortalSecurity portalSecurity) {
    if (portalSecurity.getApplication().getReCreateTable()) {
        Configuration config = new Configuration();
        SchemaExport s = new SchemaExport(config.configure());
        s.create(false, true);
    }// ww  w.jav a 2  s.  co m
    this.createDefaultRef(_DEFAULT_ROLE, portlets);
    this.createDefaultPortalByUser(portalLayout, portalSecurity);
    this.createDefaultPortalSecurity(portalSecurity);
}

From source file:org.ngrinder.infra.init.DataUpdaterTest.java

License:Apache License

@Test
public void exportDatabaseSchema() throws IOException {
    PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo();
    for (Database each : Database.values()) {
        Map<?, ?> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap();
        Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap)
                .getHibernateConfiguration();
        configuration.setProperty(Environment.DIALECT, each.getDialect());
        SchemaExport schema = new SchemaExport(configuration);
        File parentFile = new ClassPathResource("/ngrinder_datachange_logfile/db.changelog.xml").getFile()
                .getParentFile();//from   w w  w. j  a va2s .c  o m

        parentFile.mkdirs();
        File file = new File(parentFile, "schema-" + each.name().toLowerCase() + ".sql");
        System.out.println(file.getAbsolutePath());
        schema.setOutputFile(file.getAbsolutePath());
        schema.create(true, false);
    }
}

From source file:org.olat.core.commons.persistence.DatabaseSetup.java

License:Apache License

/**
 * Write database configuration to file. Includes differences to existing database. Filename: "database/setupDatabase.sql"
 */// w  ww . j ava  2s.co m
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);
    }
}

From source file:org.ow2.bonita.util.DbTool.java

License:Open Source License

/**
 * Export DB schema to the database defined in the environment.
 *//*from w ww . ja v a  2  s .c om*/
public static void recreateDb(final String domain, final String configurationName) throws Exception {
    BonitaConstants.getBonitaHomeFolder();
    final Configuration config = getConfiguration(domain, configurationName);

    if (LOG.isLoggable(Level.FINE)) {
        final SessionFactoryImplementor sessionFactory = getSessionFactory(domain,
                configurationName.replaceAll("-configuration", "-session-factory"));
        if (sessionFactory != null) {
            final Dialect dialect = sessionFactory.getDialect();
            String[] script = config.generateSchemaCreationScript(dialect);
            for (String s : script) {
                LOG.fine(s);
            }
        }
    }

    final SchemaExport schemaExport = getSchemaExport(config);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Creating schema...");
    }

    final String dbVendor = getDatabaseVendor(config);
    StringBuilder fileNamebuilder = new StringBuilder("/script/post-initdb-").append(dbVendor).append(".sql");
    schemaExport.setImportFile(fileNamebuilder.toString());
    schemaExport.create(true, true);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Schema created.");
        LOG.fine("Adding default users...");
    }
    if (EnvConstants.HB_CONFIG_CORE.equals(configurationName)) {
        addDefaultUsers(domain, configurationName);
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Default users added.");
        }
    }
}

From source file:org.photovault.common.PVDatabase.java

License:Open Source License

/**
 * Creates a new database with the parameters specified in this object and
 * populate it with given seed data./*from w  w w .  j a v  a  2 s . co  m*/
 * <P>
 * The database schema is stored in DDLUTILS XML format in resource 
 * photovault_schema.xml.
 *
 * @param user Username used when creating the SQL database.
 * @param passwd Password for the user
 * @param seedDataResource A resource URI that contains data that should be 
 * loaded to the database. This data must be in Apache DDL format. If no 
 * additional seed data is required this must be <code>null</code>
 */
public void createDatabase(String user, String passwd, String seedDataResource) {

    // Get the database schema XML file

    try {
        HibernateUtil.init(user, passwd, this);
    } catch (PhotovaultException e) {
        log.error(e.getMessage(), e);
    }
    SchemaExport schexport = new SchemaExport(HibernateUtil.getConfiguration());
    schexport.create(true, true);

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tr = s.beginTransaction();

    HibernateDAOFactory df = (HibernateDAOFactory) DAOFactory.instance(HibernateDAOFactory.class);
    df.setSession(s);
    PhotoFolderDAO folderDao = df.getPhotoFolderDAO();
    PhotoFolder topFolder = folderDao.create(PhotoFolder.ROOT_UUID, null);
    topFolder.setName("Top");
    s.save(topFolder);

    // TODO: Since the seed has only 48 significant bits this id is not really an 
    // 128-bit random number!!!
    Random rnd = new Random();
    String idStr = "";
    StringBuffer idBuf = new StringBuffer();
    for (int n = 0; n < 4; n++) {
        int r = rnd.nextInt();
        idBuf.append(Integer.toHexString(r));
    }
    idStr = idBuf.toString();

    // Create default volume
    Volume defVol = new Volume();
    defVol.setName("default_volume");
    s.save(defVol);

    File defVolMount = dataDirectory;
    if (instanceType != TYPE_SERVER) {
        defVolMount = new File(dataDirectory, "photos");
    }
    try {
        VolumeManager.instance().initVolume(defVol, defVolMount);
    } catch (PhotovaultException ex) {
        log.error(ex);
    }
    addMountPoint(defVolMount.getAbsolutePath());
    DbInfo dbInfo = new DbInfo();
    dbInfo.setCreateTime(new Date());
    dbInfo.setId(idStr);
    dbInfo.setVersion(CURRENT_SCHEMA_VERSION);
    dbInfo.setDefaultVolumeId(defVol.getId());
    s.save(dbInfo);

    s.flush();
    tr.commit();
    s.close();
}

From source file:org.photovault.common.SchemaUpdateAction.java

License:Open Source License

/**
 Upgrades database schema and content to be compatible with the current 
 version of Photovault/*from  w  ww  . j  a  v  a  2  s  .c o  m*/
 */
public void upgradeDatabase() {
    fireStatusChangeEvent(new SchemaUpdateEvent(new SchemaUpdateOperation("Altering daptabase schema"), 0));

    int oldVersion = db.getSchemaVersion();

    SchemaExport schexport = new SchemaExport(HibernateUtil.getConfiguration());
    schexport.create(true, true);

    // Alter tables to match corrent schema
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    Connection con = session.connection();
    DbInfo info = DbInfo.getDbInfo(session);
    if (info == null) {
        info = new DbInfo();
        info.setCreateTime(new Date());
        info.setId(UUID.randomUUID().toString());
        VolumeManager vm = VolumeManager.instance();
    }
    session.saveOrUpdate(info);
    session.flush();
    tx.commit();
    session.clear();
    tx = session.beginTransaction();

    /*
     TODO: Schema changes should be done using Hibernate tools. But how to 
     handle the oledd schemas?
     */
    //        try {
    //            /*
    //            TODO:
    //            Derby alter table statements created by DdlUtils have wrong syntax.
    //            Luckily we do not need to do such modifications for now. There is
    //            error report for DdlUtils (http://issues.apache.org/jira/browse/DDLUTILS-53),
    //            after it has been corrected the alterColumns flag should be set to
    //            true.
    //             */
    //            log.info( platform.getAlterTablesSql( con, dbModel ) );
    //            platform.alterTables( con, dbModel, false );
    //        } catch ( DatabaseOperationException ex ) {
    //            log.error( ex.getMessage(), ex );
    //        }

    if (oldVersion < 4) {
        // In older version hashcolumn was not included in schema so we must fill it.
        /**
         TODO: Implement this for 0.6.0
         */
        throw new IllegalStateException("Conversion from pre-0.5.0 databases not yet supported");
    }
    /*
    if ( oldVersion < 10 ) {
    // Initialize Hibernate sequence generators
    Query q = session.createQuery( "select max( rs.rawSettingId ) from RawConversionSettings rs" );
    int maxRawSettingId = (Integer) q.uniqueResult();
    q = session.createQuery( "select max( photo.id ) from PhotoInfo photo" );
    int maxPhotoId = (Integer) q.uniqueResult();
    q = session.createQuery( "select max( folder.folderId ) from PhotoFolder folder" );
    int maxFolderId = (Integer) q.uniqueResult();
    DynaBean dbInfo = dbModel.createDynaBeanFor( "unique_keys", false );
    dbInfo.set( "id_name", "hibernate_seq" );
    dbInfo.set( "next_val", new Integer( maxPhotoId+1 ) );
    platform.insert( con, dbModel, dbInfo );
    dbInfo.set( "id_name", "rawconv_id_gen" );
    dbInfo.set( "next_val", new Integer( maxRawSettingId+1 ) );
    platform.insert( con, dbModel, dbInfo );
    dbInfo.set( "id_name", "folder_id_gen" );
    dbInfo.set( "next_val", new Integer( maxFolderId+1 ) );
    platform.insert( con, dbModel, dbInfo );
            
    try {
        Statement stmt = con.createStatement();
        stmt.executeUpdate( "insert into unique_keys(hibernate_seq, values ( \"hibernate_seq\", " + (maxPhotoId+1) + " )" );
        stmt.close();
    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
    }
    }
    */

    /*
    if ( oldVersion < 11 ) {
    upgrade11( session );
    }
    */
    if (oldVersion < 12) {
        migrateToVersionedSchema();
    }

    info = DbInfo.getDbInfo(session);
    info.setVersion(db.CURRENT_SCHEMA_VERSION);
    session.flush();
    tx.commit();
    session.close();

    fireStatusChangeEvent(new SchemaUpdateEvent(SchemaUpdateOperation.UPDATE_COMPLETE, 100));

}

From source file:org.quackbot.dao.hibernate.GenericHbTest.java

License:Open Source License

@BeforeMethod
public void setupSchema() {
    LocalSessionFactoryBean session = (LocalSessionFactoryBean) context.getBean("&sessionFactory");
    SchemaExport export = new SchemaExport(session.getConfiguration());
    export.drop(false, true);/*from w  ww .  java  2s .  c  o  m*/
    export.create(false, true);
}

From source file:org.quackbot.impl.HibernateMain.java

License:Open Source License

public void firstRun() {
    LocalSessionFactoryBean session = (LocalSessionFactoryBean) context.getBean("&sessionFactory");
    SchemaExport export = new SchemaExport(session.getConfiguration());
    export.drop(false, true);/*from  ww w. ja v  a 2s .co  m*/
    export.create(false, true);

    //Start prompting the user for info
    System.out.println();
    System.out.println("--------------------------");
    System.out.println("- Quackbot Initial Setup -");
    System.out.println("--------------------------");
    System.out.println();

    if (promptForInput("Do you wish to setup initial servers now? (Y/N)", false, "Y", "y", "N", "n")
            .equalsIgnoreCase("N")) {
        System.out.println("Skipping setup. Note: You will have to setup servers manually");
        return;
    }

    while (true) {
        String server = promptForInput("What is the address of the server?", false);
        String portString = promptForInput("What is the server port? [Default: 6667]", true);
        String password = promptForInput("What is the server password? [Default: none]", true);
        boolean ssl = promptForInput("Does the server use SSL? [Default: no] (Y/N)", false, "Y", "y", "N", "n")
                .equalsIgnoreCase("Y");

        //Store
        System.out.println("Storing server");
        int port = Integer.parseInt(StringUtils.defaultIfBlank(portString, "6667"));

        //TODO
    }
}

From source file:org.springframework.integration.jpa.core.HibernateJpaOperationsTests.java

License:Apache License

/**
 *  Little helper that allows you to generate the DDL via Hibernate. The
 *  DDL is printed to the console.//from  w  ww  .  j  a  v  a2  s  . com
 */
@Test
public void generateDdl() {

    final org.hibernate.ejb.Ejb3Configuration cfg = new org.hibernate.ejb.Ejb3Configuration();

    Map<String, Object> properties = fb.getJpaPropertyMap();

    properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

    final org.hibernate.ejb.Ejb3Configuration configured = cfg.configure(fb.getPersistenceUnitInfo(),
            fb.getJpaPropertyMap());
    final Configuration configuration = configured.getHibernateConfiguration();

    final SchemaExport schemaExport;

    try {
        schemaExport = new SchemaExport(configuration, dataSource.getConnection());
    } catch (HibernateException e) {
        throw new IllegalStateException(e);
    } catch (SQLException e) {
        throw new IllegalStateException(e);
    }

    schemaExport.create(true, false);

}