Java 类org.hibernate.boot.Metadata 实例源码

项目:spanner-hibernate    文件:CloudSpannerTableExporter.java   
@Override
public String[] getSqlDropStrings(Table table, Metadata metadata)
{
    // Check for actually existing table and indices.
    if (!tableExists(table))
        return new String[] {};
    Set<String> existingIndices = getIndicesExcludingPK(table);

    if (existingIndices.isEmpty())
        return super.getSqlDropStrings(table, metadata);

    List<String> dropIndices = new ArrayList<>();
    for (String index : existingIndices)
    {
        dropIndices.add("DROP INDEX `" + index + "`");
    }
    String[] tableDrop = super.getSqlDropStrings(table, metadata);

    String[] res = new String[dropIndices.size() + tableDrop.length];
    dropIndices.toArray(res);
    System.arraycopy(tableDrop, 0, res, dropIndices.size(), tableDrop.length);

    return res;
}
项目:spanner-hibernate    文件:CloudSpannerUniqueDelegate.java   
@Override
public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata)
{
    // First check that this unique key actually is present, as this is a
    // lot faster than trying to drop it and then fail.
    initIndices();
    UniqueIndex idx = indices.getIndex(uniqueKey);
    if (idx == null)
    {
        return null;
    }
    // Remove from cache
    indices.removeIndex(uniqueKey);
    final StringBuilder buf = new StringBuilder("DROP INDEX ");
    buf.append(dialect.quote(uniqueKey.getName()));

    return buf.toString();
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected void applyConstraints(Metadata metadata) {
    File tempFile = null;
    try {
        tempFile = File.createTempFile("schema", ".sql");
        new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
                .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
        List<String> sqls = new ArrayList<>();
        for (String sql: FileUtils.readLines(tempFile)) {
            if (isApplyingConstraints(sql)) {
                sqls.add(sql);
            }
        }
        execute(sqls, true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (tempFile != null)
            tempFile.delete();
    }
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected void createTables(Metadata metadata) {
    File tempFile = null;
    try {
        tempFile = File.createTempFile("schema", ".sql");
        new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
                .setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
        List<String> sqls = new ArrayList<>();
        for (String sql: FileUtils.readLines(tempFile)) {
            if (shouldInclude(sql) && !isApplyingConstraints(sql))
                sqls.add(sql);
        }
        execute(sqls, true);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (tempFile != null)
            FileUtils.deleteFile(tempFile);
    }
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected void dropConstraints(Metadata metadata) {
    File tempFile = null;
    try {
        tempFile = File.createTempFile("schema", ".sql");
        new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
                .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
        List<String> sqls = new ArrayList<>();
        for (String sql: FileUtils.readLines(tempFile)) {
            if (isDroppingConstraints(sql))
                sqls.add(sql);
        }
        execute(sqls, false);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (tempFile != null)
            tempFile.delete();
    }
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected void cleanDatabase(Metadata metadata) {
    File tempFile = null;
    try {
        tempFile = File.createTempFile("schema", ".sql");
        new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
                .setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
        List<String> sqls = new ArrayList<>();
        for (String sql: FileUtils.readLines(tempFile)) {
            sqls.add(sql);
        }
        execute(sqls, false);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (tempFile != null)
            tempFile.delete();
    }
}
项目:gitplex-mit    文件:CleanDBCommand.java   
@Override
public void start() {
    if (Bootstrap.isServerRunning(Bootstrap.installDir)) {
        logger.error("Please stop server before cleaning database");
        System.exit(1);
    }
    checkDataVersion(false);

    Metadata metadata = buildMetadata();
    cleanDatabase(metadata);

    if (getDialect().toLowerCase().contains("hsql")) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    logger.info("Database is cleaned successfully");

    System.exit(0);
}
项目:ipf-flow-manager    文件:CustomEventRegistration.java   
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry service = serviceRegistry.getService(org.hibernate.event.service.spi.EventListenerRegistry.class);

    StandardPBEStringEncryptor encrypt = new StandardPBEStringEncryptor();
    encrypt.setPassword("test_password");
    RenderedMessageEncryptEventListener encryptListener = new RenderedMessageEncryptEventListener();
    encryptListener.setStringEncryptor(encrypt);

    RenderedMessageDecryptEventListener decryptListener = new RenderedMessageDecryptEventListener();
    decryptListener.setStringEncryptor(encrypt);

    FullTextIndexEventListener fullTextListener = new FullTextIndexEventListener();

    service.appendListeners(EventType.PRE_UPDATE, encryptListener);
    service.prependListeners(EventType.POST_UPDATE, decryptListener);
    service.appendListeners(EventType.PRE_INSERT, encryptListener);
    service.prependListeners(EventType.POST_INSERT, decryptListener);
    service.appendListeners(EventType.POST_LOAD, decryptListener);
}
项目:VoxelGamesLib    文件:HibernatePersistenceProvider.java   
@Override
public void start() {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.connection.username", config.persistence.user)
            .applySetting("hibernate.connection.password", config.persistence.pass)
            .applySetting("hibernate.connection.driver_class", config.persistence.driver)
            .applySetting("hibernate.connection.url", config.persistence.url)
            .applySetting("hibernate.dialect", config.persistence.dialect)
            .applySetting("hibernate.connection.pool_size", config.persistence.pool_size + "")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("hibernate.show_sql", config.persistence.showSQL + "")
            .build();

    MetadataSources sources = new MetadataSources(registry);

    Timings.time("RegisterDBEntities", () ->
            new Reflections().getTypesAnnotatedWith(Entity.class).forEach(sources::addAnnotatedClass));

    try {
        Metadata metadata = sources.buildMetadata();
        sessionFactory = metadata.buildSessionFactory();
    } catch (Exception e) {
        StandardServiceRegistryBuilder.destroy(registry);
        e.printStackTrace();
    }
}
项目:springJpaKata    文件:ORMStandaloneTestCase.java   
@Before
public void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
        .applySetting( "hibernate.show_sql", "true" )
        .applySetting( "hibernate.format_sql", "true" )
        .applySetting( "hibernate.hbm2ddl.auto", "update" )
        .applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
        .applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
        .applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
        .applySetting( "hibernate.connection.username", "sa" )
        .applySetting( "hibernate.connection.password", "" )
        .applySetting( "hibernate.use_sql_comment", "true" )
        ;
    Metadata metadata  = null;
    if(packageBase()== null){
    metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
    }else{
        metadata= new MetadataSources( srb.build() )
                .addAnnotatedClass(Item.class)
                .addAnnotatedClass(Offer.class)

                .addPackage(packageBase()).buildMetadata();
    }

       sf = metadata.buildSessionFactory();
   }
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Address.class).addAnnotatedClass(User.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Address.class).addAnnotatedClass(User.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
项目:springJpaKata    文件:ORMStandaloneTestCase.java   
@Before
public void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
        .applySetting( "hibernate.show_sql", "true" )
        .applySetting( "hibernate.format_sql", "true" )
        .applySetting( "hibernate.hbm2ddl.auto", "update" )
        .applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
        .applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
        .applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
        .applySetting( "hibernate.connection.username", "sa" )
        .applySetting( "hibernate.connection.password", "" )
        .applySetting( "hibernate.use_sql_comment", "true" )
        ;
    Metadata metadata  = null;
    if(packageBase()== null){
    metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
    }else{
        metadata= new MetadataSources( srb.build() )
                .addAnnotatedClass(Item.class)
                .addAnnotatedClass(Offer.class)

                .addPackage(packageBase()).buildMetadata();
    }

       sf = metadata.buildSessionFactory();
   }
项目:high-performance-java-persistence    文件:MetadataTest.java   
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
项目:juddi    文件:App.java   
/**
 * 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);
}
项目:jooby    文件:HbmTest.java   
private Block metadataBuilder() {
  return unit -> {
    MetadataBuilder mb = unit.get(MetadataBuilder.class);
    expect(mb.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE))
        .andReturn(mb);
    expect(mb.applyScanEnvironment(unit.get(ScanEnvironment.class))).andReturn(mb);

    SessionFactoryBuilder sfb = unit.mock(SessionFactoryBuilder.class);
    unit.registerMock(SessionFactoryBuilder.class, sfb);

    Metadata md = unit.mock(Metadata.class);
    expect(md.getSessionFactoryBuilder()).andReturn(sfb);

    expect(mb.build()).andReturn(md);

    unit.registerMock(Metadata.class, md);
  };
}
项目:otus_java_2017_06    文件:DBServiceImpl.java   
public DBServiceImpl() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

    Map<String, Object> settings = new HashMap<>();
    settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
    settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
    settings.put(Environment.URL, "jdbc:mysql://localhost:3306/db_example");
    settings.put(Environment.USER, "tully");
    settings.put(Environment.PASS, "tully");
    settings.put(Environment.HBM2DDL_AUTO, "create");
    settings.put(Environment.SHOW_SQL, true);
    settings.put(Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);

    // c3p0 configuration
    settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
    settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
    settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted
    settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time

    registryBuilder.applySettings(settings);

    ServiceRegistry registry = registryBuilder.build();
    MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(PhoneDataSet.class)
            .addAnnotatedClass(UserDataSet.class)
            .addAnnotatedClass(AddressDataSet.class);


    Metadata metadata = sources.getMetadataBuilder().build();
    sessionFactory = metadata.getSessionFactoryBuilder().build();
}
项目:spanner-hibernate    文件:CloudSpannerUniqueDelegate.java   
@Override
public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata)
{
    ConfigurationService config = metadata.getDatabase().getBuildingOptions().getServiceRegistry()
            .getService(ConfigurationService.class);
    if (config != null)
    {
        String value = config.getSetting("hibernate.hbm2ddl.auto", StandardConverters.STRING);
        if (!value.equalsIgnoreCase("update"))
        {
            // We should only check whether it is already present in an
            // update scenario, in all other scenarios, just return the
            // actual create statement.
            return org.hibernate.mapping.Index.buildSqlCreateIndexString(dialect, uniqueKey.getName(),
                    uniqueKey.getTable(), uniqueKey.columnIterator(), uniqueKey.getColumnOrderMap(), true,
                    metadata);
        }
    }
    // First check that this unique key is not already present, as this is a
    // lot faster than trying to create it and then fail.
    initIndices();
    UniqueIndex idx = indices.getIndex(uniqueKey);
    if (idx != null)
    {
        return null;
    }
    return org.hibernate.mapping.Index.buildSqlCreateIndexString(dialect, uniqueKey.getName(), uniqueKey.getTable(),
            uniqueKey.columnIterator(), uniqueKey.getColumnOrderMap(), true, metadata);
}
项目:spanner-hibernate    文件:CloudSpannerSchemaHandler.java   
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
    for (Object o : args)
    {
        if (o instanceof Metadata)
        {
            addAuxiliaryDatabaseObjects(((Metadata) o).getDatabase());
            break;
        }
    }
    return method.invoke(delegate, args);
}
项目:JavaEE    文件:App.java   
/**
 * Creating a session
 * @return org.hibernate.Session
 */
private Session createHibernateSession() {
    try {
        Map<String, String> settings = new HashMap<String, String>();
        settings.put("hibernate.connection.driver_class", "org.sqlite.JDBC");
        settings.put("hibernate.connection.url", "jdbc:sqlite:mysqlite.db");
        settings.put("hibernate.connection.username", "");
        settings.put("hibernate.connection.password", "");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(settings)
                .build();

        MetadataSources sources = new MetadataSources(registry)
                .addAnnotatedClass(Person.class);

        Metadata metadata = sources
                .getMetadataBuilder()
                .build();

        SessionFactory sessionFactory = metadata
                .getSessionFactoryBuilder()
                .build();

        session = sessionFactory.openSession();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }
    System.out.println("Session created successfully.");
    return session;
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected Metadata buildMetadata() {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    for (Class<? extends AbstractEntity> each: LoaderUtils.findImplementations(AbstractEntity.class, AbstractEntity.class)) {
        metadataSources.addAnnotatedClass(each);
    }

    return metadataSources.getMetadataBuilder().applyPhysicalNamingStrategy(physicalNamingStrategy).build();
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
@Sessional
@Override
public void importData(Metadata metadata, File dataDir) {
    Session session = dao.getSession();
    List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
    Collections.reverse(entityTypes);
    for (Class<?> entityType: entityTypes) {
        File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith(entityType.getSimpleName() + "s.xml");
            }

        });
        for (File file: dataFiles) {
            try {
                logger.info("Importing from data file '" + file.getName() + "'...");
                session.beginTransaction();
                VersionedDocument dom = VersionedDocument.fromFile(file);

                for (Element element: dom.getRootElement().elements()) {
                    element.detach();
                    AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
                    session.replicate(entity, ReplicationMode.EXCEPTION);
                }
                session.flush();
                session.clear();
                session.getTransaction().commit();
            } catch (Throwable e) {
                session.getTransaction().rollback();
                throw Throwables.propagate(e);
            }
        }
    }   
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
protected void validateData(Metadata metadata, File dataDir) {
    List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
    Collections.reverse(entityTypes);
    for (Class<?> entityType: entityTypes) {
        File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith(entityType.getSimpleName() + "s.xml");
            }

        });
        for (File file: dataFiles) {
            try {
                logger.info("Validating data file '" + file.getName() + "'...");
                VersionedDocument dom = VersionedDocument.fromFile(file);

                for (Element element: dom.getRootElement().elements()) {
                    element.detach();
                    AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
                    validator.validate(entity);
                }
            } catch (Throwable e) {
                throw Throwables.propagate(e);
            }
        }
    }   
}
项目:gitplex-mit    文件:ResetAdminPasswordCommand.java   
@Override
public void start() {
    if (Bootstrap.command.getArgs().length == 0) {
        logger.error("Missing password parameter. Usage: {} <new password>", Bootstrap.command.getScript());
        System.exit(1);
    }
    if (Bootstrap.isServerRunning(Bootstrap.installDir)) {
        logger.error("Please stop server before resetting admin password");
        System.exit(1);
    }

    checkDataVersion(false);

    Metadata metadata = buildMetadata();
    sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();

    User root = userManager.get(User.ROOT_ID);
    if (root == null) {
        logger.error("Server not set up yet");
        System.exit(1);
    }
    String password = Bootstrap.command.getArgs()[0];
    root.setPassword(passwordService.encryptPassword(password));
    userManager.save(root);

    // wait for a short period to have embedded db flushing data
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    sessionFactory.close();

    logger.info("Password of user '" + root.getName() + "' has been reset to: " + password);
    System.exit(0);
}
项目:gitplex-mit    文件:RestoreDBCommand.java   
private void doRestore(Metadata metadata, File dataDir) {
    migrateData(dataDir);
    validateData(metadata, dataDir);

    String dbDataVersion = checkDataVersion(true);

    if (dbDataVersion != null) {
        logger.info("Cleaning database...");
        cleanDatabase(metadata);
    }

    logger.info("Creating tables...");
    createTables(metadata);

    logger.info("Importing data into database...");
    importData(metadata, dataDir);

    logger.info("Applying foreign key constraints...");
    try {
        applyConstraints(metadata);     
    } catch (Exception e) {
        logger.error("Failed to apply database constraints", e);
        logger.info("If above error is caused by foreign key constraint violations, you may fix it via your database sql tool, "
                + "and then run {} to reapply database constraints", Command.getScript("apply_db_constraints"));
        System.exit(1);
    }
}
项目:otus_java_2017_04    文件:DBServiceImpl.java   
public DBServiceImpl() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

    Map<String, Object> settings = new HashMap<>();
    settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
    settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
    settings.put(Environment.URL, "jdbc:mysql://localhost:3306/db_example");
    settings.put(Environment.USER, "tully");
    settings.put(Environment.PASS, "tully");
    settings.put(Environment.HBM2DDL_AUTO, "create");
    settings.put(Environment.SHOW_SQL, true);
    settings.put(Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);

    // c3p0 configuration
    settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
    settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
    settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted
    settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time

    registryBuilder.applySettings(settings);

    ServiceRegistry registry = registryBuilder.build();
    MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(PhoneDataSet.class)
            .addAnnotatedClass(UserDataSet.class);


    Metadata metadata = sources.getMetadataBuilder().build();
    sessionFactory = metadata.getSessionFactoryBuilder().build();
}
项目:hibernateMaster    文件:SingleFactoryEngine.java   
@Override
    public SessionFactory buildFactory(String configFile) {
        try {
            //configuration = new Configuration().configure(configFile);
//          StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
//          .applySettings(configuration.getProperties());
//          SessionFactory factory2 = configuration.buildSessionFactory(builder.build());


            StandardServiceRegistry standardRegistry = new   StandardServiceRegistryBuilder()
                    .configure(configFile)
                    .build();

            MetadataSources metadataSources = new MetadataSources( standardRegistry );

            DomainScanner instanceFromProperties = getScanner(configFile);
            List<Class<? extends BaseDatabaseDomain>> scan = instanceFromProperties.scan(configFile);
            for(Class<? extends BaseDatabaseDomain> temp:scan){
                metadataSources.addAnnotatedClass(temp);
            }

        //  new HibernateUtil().scanDomain(metadataSources);

            Metadata metadata = metadataSources.getMetadataBuilder()
                .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
                .build();

            SessionFactory factory2 = metadata.getSessionFactoryBuilder().build();


            return factory2;
            /*ProxoolConnectionProvider aConnectionProvider;*/
        } catch (Exception e) {
            steed.util.logging.LoggerFactory.getLogger().error("创建sessionFactory失败",e);
        }
        return null;
    }
项目:Projeto-Flash    文件:HibernateUtil.java   
private static SessionFactory createSessionFactory() {
    standardRegistry = new StandardServiceRegistryBuilder()
            .configure( "hibernate.cfg.xml" )
            .build();

    Metadata metadata = new MetadataSources( standardRegistry )
            .getMetadataBuilder()
            .build();

    sessionFactory = metadata.getSessionFactoryBuilder().build();

    return sessionFactory;
}
项目:springJpaKata    文件:ORMStandaloneClassTestCase.java   
@BeforeClass
public static void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySetting("hibernate.show_sql", "true").applySetting("hibernate.format_sql", "true").applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate").applySetting("hibernate.connection.username", "sa").applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Book.class).buildMetadata();

    sf = metadata.buildSessionFactory();
}
项目:springJpaKata    文件:ORMStandaloneTestCase.java   
@Before
public void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
        .applySetting( "hibernate.show_sql", "true" )
        .applySetting( "hibernate.format_sql", "true" )
        .applySetting( "hibernate.hbm2ddl.auto", "update" )
        .applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
        .applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
        .applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
        .applySetting( "hibernate.connection.username", "sa" )
        .applySetting( "hibernate.connection.password", "" )
        .applySetting( "hibernate.use_sql_comment", "true" )
        ;
    Metadata metadata  = null;
    if(packageBase()== null){
    metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
    }else{
        metadata= new MetadataSources( srb.build() )
                .addAnnotatedClass(Item.class)
                .addAnnotatedClass(Tank.class)
                .addAnnotatedClass(Crew.class)
                .addAnnotatedClass(TankBi.class)
                .addAnnotatedClass(CrewBi.class)
                .addPackage(packageBase()).buildMetadata();
    }

       sf = metadata.buildSessionFactory();
   }
项目:springJpaKata    文件:ORMStandaloneMany2OneTestCase.java   
@Before
public void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
        .applySetting( "hibernate.show_sql", "true" )
        .applySetting( "hibernate.format_sql", "true" )
        .applySetting( "hibernate.hbm2ddl.auto", "update" )
        .applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
        .applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
        .applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
        .applySetting( "hibernate.connection.username", "sa" )
        .applySetting( "hibernate.connection.password", "" )
        .applySetting( "hibernate.use_sql_comment", "true" )
        ;
    Metadata metadata  = null;
    if(packageBase()== null){
    metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
    }else{
        metadata= new MetadataSources( srb.build() )
                .addAnnotatedClass(Product.class)
                .addAnnotatedClass(ProductCustomer.class)
                .addAnnotatedClass(ProductResource.class)
                .addAnnotatedClass(Part.class)

                .addPackage(packageBase()).buildMetadata();
    }

       sf = metadata.buildSessionFactory();
   }
项目:tiramisu    文件:HibernateUtil.java   
/**
 * Method to build the hibernate session factory.
 * 
 * @return A Hibernate SessionFactory object.
 */
private static synchronized SessionFactory buildSessionFactory() {
    try {
        if (HibernateUtil.serviceRegistry == null) {
            HibernateUtil.serviceRegistry = new StandardServiceRegistryBuilder()
                    .configure("au/com/ifti/models/hibernate/database.xml").build();
        }
        Metadata metadata = new MetadataSources(HibernateUtil.serviceRegistry).getMetadataBuilder().build();
        return metadata.getSessionFactoryBuilder().build();
    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
}
项目:dhis2-core    文件:DeletedObjectIntegrator.java   
@Override
public void integrate( Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry )
{
    final EventListenerRegistry registry = serviceRegistry.getService( EventListenerRegistry.class );

    DeletedObjectPostDeleteEventListener listener = new DeletedObjectPostDeleteEventListener();
    registry.appendListeners( EventType.POST_DELETE, listener );
}
项目:elide    文件:Util.java   
/**
 * Retrieve a hibernate session factory.
 *
 * @param hibernate5ConfigPath File path to hibernate config (i.e. hibernate-cfg.xml)
 * @param modelPackageName Name of package containing all models to be loaded by hibernate
 * @return Hibernate session factory.
 */
public static SessionFactory getSessionFactory(String hibernate5ConfigPath, String modelPackageName) {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
            .configure(new File(hibernate5ConfigPath))
            .build();
    MetadataSources sources = new MetadataSources(standardRegistry);

    getAllEntities(modelPackageName).forEach(sources::addAnnotatedClass);

    Metadata metaData =  sources.getMetadataBuilder().build();
    return metaData.getSessionFactoryBuilder().build();
}
项目:ignite    文件:HibernateL2CacheStrategySelfTest.java   
/**
 * @param accessType Cache access typr.
 * @param igniteInstanceName Name of the grid providing caches.
 * @return Session factory.
 */
private SessionFactory startHibernate(AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);

    for (Map.Entry<String, String> e : HibernateL2CacheSelfTest.hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    builder.applySetting(USE_STRUCTURED_CACHE, "true");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2");
    builder.applySetting(REGION_CACHE_PROPERTY + TIMESTAMP_CACHE, TIMESTAMP_CACHE);
    builder.applySetting(REGION_CACHE_PROPERTY + QUERY_CACHE, QUERY_CACHE);

    MetadataSources metadataSources = new MetadataSources(builder.build());

    metadataSources.addAnnotatedClass(Entity1.class);
    metadataSources.addAnnotatedClass(Entity2.class);
    metadataSources.addAnnotatedClass(Entity3.class);
    metadataSources.addAnnotatedClass(Entity4.class);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    return metadata.buildSessionFactory();
}
项目:ignite    文件:HibernateL2CacheSelfTest.java   
/**
 * Starts Hibernate.
 *
 * @param accessType Cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Session factory.
 */
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = registryBuilder();

    for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    // Use the same cache for Entity and Entity2.
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);

    StandardServiceRegistry srvcRegistry = builder.build();

    MetadataSources metadataSources = new MetadataSources(srvcRegistry);

    for (Class entityClass : getAnnotatedClasses())
        metadataSources.addAnnotatedClass(entityClass);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
        collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName() );

    return metadata.buildSessionFactory();
}
项目:high-performance-java-persistence    文件:OptimisticLockingChildUpdatesRootVersionTest.java   
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {

    final EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService( EventListenerRegistry.class );

    eventListenerRegistry.appendListeners(EventType.PERSIST, RootAwareInsertEventListener.INSTANCE);
    eventListenerRegistry.appendListeners(EventType.FLUSH_ENTITY, RootAwareUpdateAndDeleteEventListener.INSTANCE);
}