org.hibernate.service.ServiceRegistry Java Examples

The following examples show how to use org.hibernate.service.ServiceRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Oracle12cDialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
	super.contributeTypes( typeContributions, serviceRegistry );

	// account for Oracle's deprecated support for LONGVARBINARY...
	// 		prefer BLOB, unless the user opts out of it
	boolean preferLong = serviceRegistry.getService( ConfigurationService.class ).getSetting(
			PREFER_LONG_RAW,
			StandardConverters.BOOLEAN,
			false
	);

	if ( !preferLong ) {
		typeContributions.contributeType( MaterializedBlobType.INSTANCE, "byte[]", byte[].class.getName() );
		typeContributions.contributeType( WrappedMaterializedBlobType.INSTANCE, "Byte[]", Byte[].class.getName() );
	}
}
 
Example #2
Source File: DefaultMergeEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private EntityCopyObserver createEntityCopyObserver(SessionFactoryImplementor sessionFactory) {
	final ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
	if ( entityCopyObserverStrategy == null ) {
		final ConfigurationService configurationService
				= serviceRegistry.getService( ConfigurationService.class );
		entityCopyObserverStrategy = configurationService.getSetting(
				AvailableSettings.MERGE_ENTITY_COPY_OBSERVER,
				new ConfigurationService.Converter<String>() {
					@Override
					public String convert(Object value) {
						return value.toString();
					}
				},
				EntityCopyNotAllowedObserver.SHORT_NAME
		);
		LOG.debugf( "EntityCopyObserver strategy: %s", entityCopyObserverStrategy );
	}
	final StrategySelector strategySelector = serviceRegistry.getService( StrategySelector.class );
	return strategySelector.resolveStrategy( EntityCopyObserver.class, entityCopyObserverStrategy );
}
 
Example #3
Source File: PostgreSQLJsonBinaryTypeProgrammaticConfigurationTest.java    From hibernate-types with Apache License 2.0 6 votes vote down vote up
@Override
protected void additionalProperties(Properties properties) {
    CustomObjectMapperSupplier customObjectMapperSupplier = new CustomObjectMapperSupplier();
    final JsonBinaryType jsonBinaryType = new JsonBinaryType(customObjectMapperSupplier.get(), Location.class);

    properties.put( "hibernate.type_contributors", new TypeContributorList() {
        @Override
        public List<TypeContributor> getTypeContributors() {
            List<TypeContributor> typeContributors = new ArrayList<TypeContributor>();
            typeContributors.add(new TypeContributor() {
                @Override
                public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
                    typeContributions.contributeType(
                        jsonBinaryType, "location"
                    );
                }
            });
            return typeContributors;
        }
    });
}
 
Example #4
Source File: HibernateUtil.java    From lambda-rds-mysql with Apache License 2.0 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    if (null != sessionFactory)
        return sessionFactory;
    
    Configuration configuration = new Configuration();

    String jdbcUrl = "jdbc:mysql://"
            + System.getenv("RDS_HOSTNAME")
            + "/"
            + System.getenv("RDS_DB_NAME");
    
    configuration.setProperty("hibernate.connection.url", jdbcUrl);
    configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME"));
    configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD"));

    configuration.configure();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    try {
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        System.err.println("Initial SessionFactory creation failed." + e);
        throw new ExceptionInInitializerError(e);
    }
    return sessionFactory;
}
 
Example #5
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(EnumSet<TargetType> targetTypes, Action action, Metadata metadata, ServiceRegistry serviceRegistry) {
	if ( action == Action.NONE ) {
		LOG.debug( "Skipping SchemaExport as Action.NONE was passed" );
		return;
	}

	if ( targetTypes.isEmpty() ) {
		LOG.debug( "Skipping SchemaExport as no targets were specified" );
		return;
	}

	exceptions.clear();

	LOG.runningHbm2ddlSchemaExport();

	final TargetDescriptor targetDescriptor = buildTargetDescriptor( targetTypes, outputFile, serviceRegistry );

	doExecution( action, needsJdbcConnection( targetTypes ), metadata, serviceRegistry, targetDescriptor );
}
 
Example #6
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static TargetDescriptor buildTargetDescriptor(
		EnumSet<TargetType> targetTypes,
		String outputFile,
		ServiceRegistry serviceRegistry) {
	final ScriptTargetOutput scriptTarget;
	if ( targetTypes.contains( TargetType.SCRIPT ) ) {
		if ( outputFile == null ) {
			throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
		}
		scriptTarget = Helper.interpretScriptTargetSetting(
				outputFile,
				serviceRegistry.getService( ClassLoaderService.class ),
				(String) serviceRegistry.getService( ConfigurationService.class ).getSettings().get( AvailableSettings.HBM2DDL_CHARSET_NAME )
		);
	}
	else {
		scriptTarget = null;
	}

	return new TargetDescriptorImpl( targetTypes, scriptTarget );
}
 
Example #7
Source File: SchemaValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void validate(Metadata metadata, ServiceRegistry serviceRegistry) {
	LOG.runningSchemaValidator();

	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );

	final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class );

	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			ExceptionHandlerHaltImpl.INSTANCE
	);

	tool.getSchemaValidator( config ).doValidation( metadata, executionOptions );
}
 
Example #8
Source File: DatabaseInformationImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public DatabaseInformationImpl(
		ServiceRegistry serviceRegistry,
		JdbcEnvironment jdbcEnvironment,
		DdlTransactionIsolator ddlTransactionIsolator,
		Namespace.Name defaultNamespace) throws SQLException {
	this.jdbcEnvironment = jdbcEnvironment;

	this.extractionContext = new ImprovedExtractionContextImpl(
			serviceRegistry,
			jdbcEnvironment,
			ddlTransactionIsolator,
			defaultNamespace.getCatalog(),
			defaultNamespace.getSchema(),
			this
	);

	// todo : make this pluggable
	this.extractor = new InformationExtractorJdbcDatabaseMetaDataImpl( extractionContext );

	// because we do not have defined a way to locate sequence info by name
	initializeSequences();
}
 
Example #9
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry getStandardServiceRegistry(ServiceRegistry serviceRegistry) {
	if ( serviceRegistry == null ) {
		throw new HibernateException( "ServiceRegistry passed to MetadataBuilder cannot be null" );
	}

	if ( StandardServiceRegistry.class.isInstance( serviceRegistry ) ) {
		return ( StandardServiceRegistry ) serviceRegistry;
	}
	else if ( BootstrapServiceRegistry.class.isInstance( serviceRegistry ) ) {
		log.debugf(
				"ServiceRegistry passed to MetadataBuilder was a BootstrapServiceRegistry; this likely wont end well" +
						"if attempt is made to build SessionFactory"
		);
		return new StandardServiceRegistryBuilder( (BootstrapServiceRegistry) serviceRegistry ).build();
	}
	else {
		throw new HibernateException(
				String.format(
						"Unexpected type of ServiceRegistry [%s] encountered in attempt to build MetadataBuilder",
						serviceRegistry.getClass().getName()
				)
		);
	}
}
 
Example #10
Source File: SequenceGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("StatementWithEmptyBody")
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	DeprecationLogger.DEPRECATION_LOGGER.deprecatedSequenceGenerator( getClass().getName() );

	identifierType = type;

	final ObjectNameNormalizer normalizer = (ObjectNameNormalizer) params.get( IDENTIFIER_NORMALIZER );
	logicalQualifiedSequenceName = QualifiedNameParser.INSTANCE.parse(
			ConfigurationHelper.getString( SEQUENCE, params, "hibernate_sequence" ),
			normalizer.normalizeIdentifierQuoting( params.getProperty( CATALOG ) ),
			normalizer.normalizeIdentifierQuoting( params.getProperty( SCHEMA ) )
	);

	if ( params.containsKey( PARAMETERS ) ) {
		LOG.warn(
				"Use of 'parameters' config setting is no longer supported; " +
						"to specify initial-value or increment use the " +
						"org.hibernate.id.enhanced.SequenceStyleGenerator generator instead."
		);
	}
}
 
Example #11
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String determineCurrentSchemaName(
		DatabaseMetaData databaseMetaData,
		ServiceRegistry serviceRegistry,
		Dialect dialect) throws SQLException {
	final SchemaNameResolver schemaNameResolver;

	final Object setting = serviceRegistry.getService( ConfigurationService.class ).getSettings().get( SCHEMA_NAME_RESOLVER );
	if ( setting == null ) {
		schemaNameResolver = dialect.getSchemaNameResolver();
	}
	else {
		schemaNameResolver = serviceRegistry.getService( StrategySelector.class ).resolveDefaultableStrategy(
				SchemaNameResolver.class,
				setting,
				dialect.getSchemaNameResolver()
		);
	}

	try {
		return schemaNameResolver.resolveSchemaName( databaseMetaData.getConnection(), dialect );
	}
	catch (Exception e) {
		log.debug( "Unable to resolve connection default schema", e );
		return null;
	}
}
 
Example #12
Source File: IdentifierGeneration.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine the name of the sequence (or table if this resolves to a physical table)
 * to use.
 *
 * @param params The params supplied in the generator config (plus some standard useful extras).
 * @return The sequence name
 */
static QualifiedName determineSequenceName(Properties params, ServiceRegistry serviceRegistry) {
	final String sequencePerEntitySuffix = ConfigurationHelper.getString( SequenceStyleGenerator.CONFIG_SEQUENCE_PER_ENTITY_SUFFIX, params, SequenceStyleGenerator.DEF_SEQUENCE_SUFFIX );

	String fallbackSequenceName = SequenceStyleGenerator.DEF_SEQUENCE_NAME;
	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( Settings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackSequenceName = generatorName;
		}
	}

	// JPA_ENTITY_NAME value honors <class ... entity-name="..."> (HBM) and @Entity#name (JPA) overrides.
	final String defaultSequenceName = ConfigurationHelper.getBoolean( SequenceStyleGenerator.CONFIG_PREFER_SEQUENCE_PER_ENTITY, params, false )
			? params.getProperty( SequenceStyleGenerator.JPA_ENTITY_NAME ) + sequencePerEntitySuffix
			: fallbackSequenceName;

	final String sequenceName = ConfigurationHelper.getString( SequenceStyleGenerator.SEQUENCE_PARAM, params, defaultSequenceName );
	if ( sequenceName.contains( "." ) ) {
		return QualifiedNameParser.INSTANCE.parse( sequenceName );
	}
	else {
		JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema =  jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		return new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( sequenceName )
		);
	}
}
 
Example #13
Source File: IdentifierGeneration.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
static QualifiedName determineTableName(Properties params, ServiceRegistry serviceRegistry) {
	String fallbackTableName = TableGenerator.DEF_TABLE;
	final Boolean preferGeneratorNameAsDefaultName = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( Settings.PREFER_GENERATOR_NAME_AS_DEFAULT_SEQUENCE_NAME, StandardConverters.BOOLEAN, true );
	if ( preferGeneratorNameAsDefaultName ) {
		final String generatorName = params.getProperty( IdentifierGenerator.GENERATOR_NAME );
		if ( StringHelper.isNotEmpty( generatorName ) ) {
			fallbackTableName = generatorName;
		}
	}

	String tableName = ConfigurationHelper.getString( TableGenerator.TABLE_PARAM, params, fallbackTableName );

	QualifiedNameParser.NameParts qualifiedTableName;
	if ( tableName.contains( "." ) ) {
		qualifiedTableName = QualifiedNameParser.INSTANCE.parse( tableName );
	}
	else {
		JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
		// todo : need to incorporate implicit catalog and schema names
		final Identifier catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( CATALOG, params )
		);
		final Identifier schema = jdbcEnvironment.getIdentifierHelper().toIdentifier(
				ConfigurationHelper.getString( SCHEMA, params )
		);
		qualifiedTableName = new QualifiedNameParser.NameParts(
				catalog,
				schema,
				jdbcEnvironment.getIdentifierHelper().toIdentifier( tableName )
		);
	}
	return qualifiedTableName;
}
 
Example #14
Source File: SequenceReactiveIdentifierGenerator.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	Dialect dialect = jdbcEnvironment.getDialect();

	qualifiedSequenceName = determineSequenceName( params, serviceRegistry );

	// allow physical naming strategies a chance to kick in
	String renderedSequenceName = jdbcEnvironment.getQualifiedObjectNameFormatter()
			.format( qualifiedSequenceName, dialect );

	sql = dialect.getSequenceNextValString( renderedSequenceName );
}
 
Example #15
Source File: ReactiveServiceRegistryBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Destroy a service registry.  Applications should only destroy registries they have explicitly created.
 *
 * @param serviceRegistry The registry to be closed.
 */
public static void destroy(ServiceRegistry serviceRegistry) {
    if ( serviceRegistry == null ) {
        return;
    }

    ( (StandardServiceRegistryImpl) serviceRegistry ).destroy();
}
 
Example #16
Source File: XmlMappingBinderAccess.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public XmlMappingBinderAccess(ServiceRegistry serviceRegistry) {
	this.classLoaderService = serviceRegistry.getService( ClassLoaderService.class );

	// NOTE : The boolean here indicates whether or not to perform validation as we load XML documents.
	// Should we expose this setting?  Disabling would speed up JAXP and JAXB at runtime, but potentially
	// at the cost of less obvious errors when a document is not valid.
	this.mappingBinder = new MappingBinder( serviceRegistry.getService( ClassLoaderService.class ), true );
}
 
Example #17
Source File: TestHibernateTypes.java    From jasypt with Apache License 2.0 5 votes vote down vote up
private void initialize() {
    registerEncryptors();
    
    // Configure Hibernate and open session
	ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
	    .applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
           .applySetting("hibernate.connection.url", 
               "jdbc:hsqldb:mem:jasypttestdb")
           .applySetting("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
           .applySetting("hibernate.connection.username", "sa")
           .applySetting("hibernate.connection.password", "")
           .applySetting("hibernate.connection.pool_size", "10");
	ServiceRegistry serviceRegistry = serviceRegistryBuilder.buildServiceRegistry();
	
	hbConf = new Configuration();
	sessionFactory = hbConf
           .addClass(User.class)
           .setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
           .setProperty("hibernate.connection.url", 
                   "jdbc:hsqldb:mem:jasypttestdb")
           .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
           .setProperty("hibernate.connection.username", "sa")
           .setProperty("hibernate.connection.password", "")
           .setProperty("hibernate.connection.pool_size", "10")
           .buildSessionFactory(serviceRegistry);
	session = sessionFactory.openSession();
    
	initDB();		
	
	generateData();
}
 
Example #18
Source File: StandardServiceRegistryBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Destroy a service registry.  Applications should only destroy registries they have explicitly created.
 *
 * @param serviceRegistry The registry to be closed.
 */
public static void destroy(ServiceRegistry serviceRegistry) {
	if ( serviceRegistry == null ) {
		return;
	}

	( (StandardServiceRegistryImpl) serviceRegistry ).destroy();
}
 
Example #19
Source File: HibernateUtil.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static SessionFactory getSessionFactory(Properties properties) {
    Configuration configuration = new Configuration();

    configuration.setProperties(properties);
    configuration.addAnnotatedClass(UserData.class);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example #20
Source File: TableGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	storeLastUsedValue = serviceRegistry.getService( ConfigurationService.class )
			.getSetting( AvailableSettings.TABLE_GENERATOR_STORE_LAST_USED, StandardConverters.BOOLEAN, true );
	identifierType = type;

	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );

	qualifiedTableName = determineGeneratorTableName( params, jdbcEnvironment, serviceRegistry );
	segmentColumnName = determineSegmentColumnName( params, jdbcEnvironment );
	valueColumnName = determineValueColumnName( params, jdbcEnvironment );

	segmentValue = determineSegmentValue( params );

	segmentValueLength = determineSegmentColumnSize( params );
	initialValue = determineInitialValue( params );
	incrementSize = determineIncrementSize( params );

	final String optimizationStrategy = ConfigurationHelper.getString(
			OPT_PARAM,
			params,
			OptimizerFactory.determineImplicitOptimizerName( incrementSize, params )
	);
	int optimizerInitialValue = ConfigurationHelper.getInt( INITIAL_PARAM, params, -1 );
	optimizer = OptimizerFactory.buildOptimizer(
			optimizationStrategy,
			identifierType.getReturnedClass(),
			incrementSize,
			optimizerInitialValue
	);
}
 
Example #21
Source File: RecordableBootstrap.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Destroy a service registry. Applications should only destroy registries they
 * have explicitly created.
 *
 * @param serviceRegistry The registry to be closed.
 */
public static void destroy(ServiceRegistry serviceRegistry) {
    if (serviceRegistry == null) {
        return;
    }

    ((StandardServiceRegistryImpl) serviceRegistry).destroy();
}
 
Example #22
Source File: FastBootEntityManagerFactoryBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionFactoryClosed(SessionFactory sessionFactory) {
    SessionFactoryImplementor sfi = ((SessionFactoryImplementor) sessionFactory);
    sfi.getServiceRegistry().destroy();
    ServiceRegistry basicRegistry = sfi.getServiceRegistry().getParentServiceRegistry();
    ((ServiceRegistryImplementor) basicRegistry).destroy();
}
 
Example #23
Source File: Hibernate5DDLExporter.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
private MetadataSources mapAnnotatedClasses(ServiceRegistry serviceRegistry) {
    MetadataSources sources = new MetadataSources(serviceRegistry);

    final Reflections reflections = new Reflections();
    for (final Class<?> mappedSuperClass : reflections.getTypesAnnotatedWith(MappedSuperclass.class)) {
        sources.addAnnotatedClass(mappedSuperClass);
        System.out.println("Mapped = " + mappedSuperClass.getName());
    }
    for (final Class<?> entityClasses : reflections.getTypesAnnotatedWith(Entity.class)) {
        sources.addAnnotatedClass(entityClasses);
        System.out.println("Mapped = " + entityClasses.getName());
    }
    return sources;
}
 
Example #24
Source File: RedirectionSchemaInitializer.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
RedirectionSchemaInitializer(DataSource dataSource, String sourceName, Dialect dialect, Metadata metadata,
        ServiceRegistry registry, Schema schema, ApplicationContext applicationContext) {
    super(dataSource, sourceName, applicationContext);
    this.dialect = dialect;
    this.metadata = metadata;
    this.schema = schema;
    this.registry = registry;
}
 
Example #25
Source File: SchemaBuilderUtility.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public static Metadata generateHbmModel(ConnectionProvider provider, Dialect dialect) throws SQLException {
    MetadataSources metadataSources = new MetadataSources();
    ServiceRegistry registry = metadataSources.getServiceRegistry();

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) registry).applySetting(AvailableSettings.DIALECT, TeiidDialect.class)
            .addService(ConnectionProvider.class, provider).addService(JdbcEnvironment.class,
                    new JdbcEnvironmentImpl(provider.getConnection().getMetaData(), dialect))
            .build();

    MetadataBuildingOptions options = new MetadataBuildingOptionsImpl(serviceRegistry);
    BootstrapContext bootstrapContext = new BootstrapContextImpl( serviceRegistry, options );

    ReverseEngineeringStrategy strategy = new DefaultReverseEngineeringStrategy();

    InFlightMetadataCollectorImpl metadataCollector =  new InFlightMetadataCollectorImpl(bootstrapContext, options);
    MetadataBuildingContext buildingContext = new MetadataBuildingContextRootImpl(bootstrapContext, options,
            metadataCollector);

    JDBCBinder binder = new JDBCBinder(serviceRegistry, new Properties(), buildingContext, strategy, false);
    Metadata metadata = metadataCollector.buildMetadataInstance(buildingContext);
    binder.readFromDatabase(null, null, buildMapping(metadata));
    HibernateMappingExporter exporter = new HibernateMappingExporter() {
        @Override
        public Metadata getMetadata() {
            return metadata;
        }
    };
    exporter.start();
    return metadata;
}
 
Example #26
Source File: SchemaBuilderUtility.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
TeiidJDBCBinder(ServiceRegistry serviceRegistry, Properties properties, MetadataBuildingContext mdbc,
        ReverseEngineeringStrategy revengStrategy, boolean preferBasicCompositeIds, InFlightMetadataCollectorImpl metadataCollector, MetadataFactory source) {
    super(serviceRegistry, properties, mdbc, revengStrategy, preferBasicCompositeIds);
    this.metadataCollector = metadataCollector;
    this.source = source;
    this.strategy = revengStrategy;
}
 
Example #27
Source File: Configuration.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static BootstrapServiceRegistry getBootstrapRegistry(ServiceRegistry serviceRegistry) {
	if ( BootstrapServiceRegistry.class.isInstance( serviceRegistry ) ) {
		return (BootstrapServiceRegistry) serviceRegistry;
	}
	else if ( StandardServiceRegistry.class.isInstance( serviceRegistry ) ) {
		final StandardServiceRegistry ssr = (StandardServiceRegistry) serviceRegistry;
		return (BootstrapServiceRegistry) ssr.getParentServiceRegistry();
	}

	throw new HibernateException(
			"No ServiceRegistry was passed to Configuration#buildSessionFactory " +
					"and could not determine how to locate BootstrapServiceRegistry " +
					"from Configuration instantiation"
	);
}
 
Example #28
Source File: Property.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected ServiceRegistry resolveServiceRegistry() {
	if ( getPersistentClass() != null ) {
		return getPersistentClass().getServiceRegistry();
	}
	if ( getValue() != null ) {
		return getValue().getServiceRegistry();
	}
	throw new HibernateException( "Could not resolve ServiceRegistry" );
}
 
Example #29
Source File: SchemaUpdate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(EnumSet<TargetType> targetTypes, Metadata metadata, ServiceRegistry serviceRegistry) {
	if ( targetTypes.isEmpty() ) {
		LOG.debug( "Skipping SchemaExport as no targets were specified" );
		return;
	}

	exceptions.clear();
	LOG.runningHbm2ddlSchemaUpdate();

	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
	config.put( AvailableSettings.HBM2DDL_DELIMITER, delimiter );
	config.put( AvailableSettings.FORMAT_SQL, format );

	final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class );

	final ExceptionHandler exceptionHandler = haltOnError
			? ExceptionHandlerHaltImpl.INSTANCE
			: new ExceptionHandlerCollectingImpl();

	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			exceptionHandler
	);

	final TargetDescriptor targetDescriptor = SchemaExport.buildTargetDescriptor( targetTypes, outputFile, serviceRegistry );

	try {
		tool.getSchemaMigrator( config ).doMigration( metadata, executionOptions, targetDescriptor );
	}
	finally {
		if ( exceptionHandler instanceof ExceptionHandlerCollectingImpl ) {
			exceptions.addAll( ( (ExceptionHandlerCollectingImpl) exceptionHandler ).getExceptions() );
		}
	}
}
 
Example #30
Source File: ExtractionContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ExtractionContextImpl(
		ServiceRegistry serviceRegistry,
		JdbcEnvironment jdbcEnvironment,
		JdbcConnectionAccess jdbcConnectionAccess,
		DatabaseObjectAccess registeredTableAccess,
		Identifier defaultCatalogName,
		Identifier defaultSchemaName) {
	this.serviceRegistry = serviceRegistry;
	this.jdbcEnvironment = jdbcEnvironment;
	this.jdbcConnectionAccess = jdbcConnectionAccess;
	this.registeredTableAccess = registeredTableAccess;
	this.defaultCatalogName = defaultCatalogName;
	this.defaultSchemaName = defaultSchemaName;
}