org.hibernate.boot.registry.BootstrapServiceRegistry Java Examples

The following examples show how to use org.hibernate.boot.registry.BootstrapServiceRegistry. 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: BootstrapAPIIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException {

    BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder()
            .build();

    ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry)
            // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient.
            //.configure()
            .build();

    MetadataSources metadataSources = new MetadataSources(standardRegistry);
    metadataSources.addAnnotatedClass(Movie.class);

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

    sessionFactory = metadata.buildSessionFactory();
    assertNotNull(sessionFactory);
    sessionFactory.close();
}
 
Example #2
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 #3
Source File: SchemaValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs parsedArgs) throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

	if ( parsedArgs.cfgXmlFile != null ) {
		ssrBuilder.configure( parsedArgs.cfgXmlFile );
	}

	if ( parsedArgs.propertiesFile != null ) {
		Properties properties = new Properties();
		properties.load( new FileInputStream( parsedArgs.propertiesFile ) );
		ssrBuilder.applySettings( properties );
	}

	return ssrBuilder.build();
}
 
Example #4
Source File: SchemaUpdate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs parsedArgs) throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

	if ( parsedArgs.cfgXmlFile != null ) {
		ssrBuilder.configure( parsedArgs.cfgXmlFile );
	}

	if ( parsedArgs.propertiesFile != null ) {
		Properties props = new Properties();
		props.load( new FileInputStream( parsedArgs.propertiesFile ) );
		ssrBuilder.applySettings( props );
	}

	return ssrBuilder.build();
}
 
Example #5
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs commandLineArgs)
		throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

	if ( commandLineArgs.cfgXmlFile != null ) {
		ssrBuilder.configure( commandLineArgs.cfgXmlFile );
	}

	Properties properties = new Properties();
	if ( commandLineArgs.propertiesFile != null ) {
		properties.load( new FileInputStream( commandLineArgs.propertiesFile ) );
	}
	ssrBuilder.applySettings( properties );

	return ssrBuilder.build();
}
 
Example #6
Source File: TeiidServer.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
private Metadata getMetadata(Set<BeanDefinition> components, PhysicalNamingStrategy namingStrategy,
        MetadataFactory mf) {
    ServiceRegistry registry = metadataSources.getServiceRegistry();
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) registry).applySetting(AvailableSettings.DIALECT, TeiidDialect.class)
            .build();
    // Generate Hibernate model based on @Entity definitions
    for (BeanDefinition c : components) {
        try {
            Class<?> clazz = Class.forName(c.getBeanClassName());
            metadataSources.addAnnotatedClass(clazz);
        } catch (ClassNotFoundException e) {
        }
    }
    return metadataSources.getMetadataBuilder(serviceRegistry).applyPhysicalNamingStrategy(namingStrategy).build();
}
 
Example #7
Source File: PreconfiguredReactiveServiceRegistryBuilder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public StandardServiceRegistryImpl buildNewServiceRegistry() {
    final BootstrapServiceRegistry bootstrapServiceRegistry = buildEmptyBootstrapServiceRegistry();

    // Can skip, it's only deprecated stuff:
    // applyServiceContributingIntegrators( bootstrapServiceRegistry );

    // This is NOT deprecated stuff.. yet they will at best contribute stuff we
    // already recorded as part of #applyIntegrator, #addInitiator, #addService
    // applyServiceContributors( bootstrapServiceRegistry );

    final Map settingsCopy = new HashMap();
    settingsCopy.putAll(configurationValues);

    destroyedRegistry.resetAndReactivate(bootstrapServiceRegistry, initiators, providedServices, settingsCopy);
    return destroyedRegistry;
}
 
Example #8
Source File: PreconfiguredServiceRegistryBuilder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public StandardServiceRegistryImpl buildNewServiceRegistry() {
    final BootstrapServiceRegistry bootstrapServiceRegistry = buildEmptyBootstrapServiceRegistry();

    // Can skip, it's only deprecated stuff:
    // applyServiceContributingIntegrators( bootstrapServiceRegistry );

    // This is NOT deprecated stuff.. yet they will at best contribute stuff we
    // already recorded as part of #applyIntegrator, #addInitiator, #addService
    // applyServiceContributors( bootstrapServiceRegistry );

    final Map settingsCopy = new HashMap();
    settingsCopy.putAll(configurationValues);

    destroyedRegistry.resetAndReactivate(bootstrapServiceRegistry, initiators, providedServices, settingsCopy);
    return destroyedRegistry;

    //		return new StandardServiceRegistryImpl(
    //				true,
    //				bootstrapServiceRegistry,
    //				initiators,
    //				providedServices,
    //				settingsCopy
    //		);
}
 
Example #9
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 #10
Source File: Hbm2ddl.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	String locationPattern = "classpath:/org/wallride/domain/*";

	final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build();
	final MetadataSources metadataSources = new MetadataSources(registry);
	final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry);

	registryBuilder.applySetting(AvailableSettings.DIALECT, ExtendedMySQL5InnoDBDialect.class.getCanonicalName());
	registryBuilder.applySetting(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true);
	registryBuilder.applySetting(AvailableSettings.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategySnakeCaseImpl.class);

	final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
	final Resource[] resources = resourcePatternResolver.getResources(locationPattern);
	final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	for (Resource resource : resources) {
		MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
		AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
		if (metadata.hasAnnotation(Entity.class.getName())) {
			metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName()));
		}
	}

	final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build();
	final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl);

	new SchemaExport()
			.setHaltOnError(true)
			.setDelimiter(";")
			.create(EnumSet.of(TargetType.STDOUT), metadataBuilder.build());
}
 
Example #11
Source File: StandardServiceRegistryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a StandardServiceRegistryImpl.  Should not be instantiated directly; use
 * {@link org.hibernate.boot.registry.StandardServiceRegistryBuilder} instead
 *
 * @param autoCloseRegistry See discussion on
 * {@link org.hibernate.boot.registry.StandardServiceRegistryBuilder#disableAutoClose}
 * @param bootstrapServiceRegistry The bootstrap service registry.
 * @param serviceInitiators Any StandardServiceInitiators provided by the user to the builder
 * @param providedServices Any standard services provided directly to the builder
 * @param configurationValues Configuration values
 *
 * @see org.hibernate.boot.registry.StandardServiceRegistryBuilder
 */
@SuppressWarnings( {"unchecked"})
public StandardServiceRegistryImpl(
		boolean autoCloseRegistry,
		BootstrapServiceRegistry bootstrapServiceRegistry,
		List<StandardServiceInitiator> serviceInitiators,
		List<ProvidedService> providedServices,
		Map<?, ?> configurationValues) {
	super( bootstrapServiceRegistry, autoCloseRegistry );

	this.configurationValues = configurationValues;

	try {
		// process initiators
		for ( ServiceInitiator initiator : serviceInitiators ) {
			createServiceBinding( initiator );
		}

		// then, explicitly provided service instances
		for ( ProvidedService providedService : providedServices ) {
			createServiceBinding( providedService );
		}
	}
	catch (RuntimeException e) {
		visitServiceBindings( binding -> binding.getLifecycleOwner().stopService( binding ) );
		throw e;
	}
}
 
Example #12
Source File: AbstractServiceRegistryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AbstractServiceRegistryImpl(
		BootstrapServiceRegistry bootstrapServiceRegistry,
		boolean autoCloseRegistry) {
	if ( ! ServiceRegistryImplementor.class.isInstance( bootstrapServiceRegistry ) ) {
		throw new IllegalArgumentException( "ServiceRegistry parent needs to implement ServiceRegistryImplementor" );
	}
	this.parent = (ServiceRegistryImplementor) bootstrapServiceRegistry;
	this.allowCrawling = ConfigurationHelper.getBoolean( ALLOW_CRAWLING, Environment.getProperties(), true );

	this.autoCloseRegistry = autoCloseRegistry;
	this.parent.registerChild( this );
}
 
Example #13
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 #14
Source File: SchemaBuilderUtility.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public void generateVBLSchema(ApplicationContext context, MetadataFactory source, MetadataFactory target,
        Dialect dialect, MetadataSources metadataSources) {
    generateVBLSchema(source, target);
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) metadataSources.getServiceRegistry())
            .applySetting(AvailableSettings.DIALECT, dialect).build();
    ArtifactCollector files = generateHibernateModel(source, serviceRegistry);
    for (File f : files.getFiles("hbm.xml")) {
        metadataSources.addFile(f);
    }
}
 
Example #15
Source File: PreconfiguredReactiveServiceRegistryBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private BootstrapServiceRegistry buildEmptyBootstrapServiceRegistry() {

        // N.B. support for custom IntegratorProvider injected via Properties (as
        // instance) removed

        // N.B. support for custom StrategySelector is not implemented yet

        final StrategySelectorImpl strategySelector = new StrategySelectorImpl(FlatClassLoaderService.INSTANCE);

        return new BootstrapServiceRegistryImpl(true,
                FlatClassLoaderService.INSTANCE,
                strategySelector, // new MirroringStrategySelector(),
                new MirroringIntegratorService(integrators));
    }
 
Example #16
Source File: PreconfiguredServiceRegistryBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private BootstrapServiceRegistry buildEmptyBootstrapServiceRegistry() {

        // N.B. support for custom IntegratorProvider injected via Properties (as
        // instance) removed

        // N.B. support for custom StrategySelector is not implemented yet

        final StrategySelectorImpl strategySelector = new StrategySelectorImpl(FlatClassLoaderService.INSTANCE);

        return new BootstrapServiceRegistryImpl(true,
                FlatClassLoaderService.INSTANCE,
                strategySelector, // new MirroringStrategySelector(),
                new MirroringIntegratorService(integrators));
    }
 
Example #17
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private BootstrapServiceRegistry buildBootstrapServiceRegistry(ClassLoaderService providedClassLoaderService) {

        // N.B. support for custom IntegratorProvider injected via Properties (as
        // instance) removed

        final QuarkusIntegratorServiceImpl integratorService = new QuarkusIntegratorServiceImpl(providedClassLoaderService);
        final QuarkusStrategySelectorBuilder strategySelectorBuilder = new QuarkusStrategySelectorBuilder();
        final StrategySelector strategySelector = strategySelectorBuilder.buildSelector(providedClassLoaderService);
        return new BootstrapServiceRegistryImpl(true, providedClassLoaderService, strategySelector, integratorService);
    }
 
Example #18
Source File: ReactiveServiceRegistryBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Intended for use exclusively from JPA boot-strapping, or extensions of
 * this class. Consider this an SPI.
 *
 * @see #forJpa
 */
protected ReactiveServiceRegistryBuilder(
        BootstrapServiceRegistry bootstrapServiceRegistry,
        Map settings,
        LoadedConfig loadedConfig) {
    this.bootstrapServiceRegistry = bootstrapServiceRegistry;
    this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
    this.settings = settings;
    this.aggregatedCfgXml = loadedConfig;
    this.initiators = defaultReactiveInitiatorList();
}
 
Example #19
Source File: RecordableBootstrap.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private RecordableBootstrap(BootstrapServiceRegistry bootstrapServiceRegistry, Map properties,
        LoadedConfig loadedConfigBaseline) {
    super(bootstrapServiceRegistry, properties, loadedConfigBaseline, null);
    this.settings = properties;
    this.bootstrapServiceRegistry = bootstrapServiceRegistry;
    this.aggregatedCfgXml = loadedConfigBaseline;
    this.initiators = standardInitiatorList();
}
 
Example #20
Source File: JpaConfiguration.java    From micronaut-sql with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the standard service registry builder.
 *
 * @param bootstrapServiceRegistry The {@link BootstrapServiceRegistry} instance
 * @return The {@link StandardServiceRegistryBuilder} instance
 */
@SuppressWarnings("WeakerAccess")
protected StandardServiceRegistryBuilder createStandServiceRegistryBuilder(BootstrapServiceRegistry bootstrapServiceRegistry) {
    return new StandardServiceRegistryBuilder(
            bootstrapServiceRegistry
    );
}
 
Example #21
Source File: BaseCoreFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected StandardServiceRegistryImpl buildServiceRegistry(BootstrapServiceRegistry bootRegistry, Configuration configuration) {
  Properties properties = new Properties();
  properties.putAll( configuration.getProperties() );
  ConfigurationHelper.resolvePlaceHolders( properties );

  StandardServiceRegistryBuilder cfgRegistryBuilder = configuration.getStandardServiceRegistryBuilder();

  StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder( bootRegistry, cfgRegistryBuilder.getAggregatedCfgXml() )
      .applySettings( properties );

  prepareBasicRegistryBuilder( registryBuilder );
  return (StandardServiceRegistryImpl) registryBuilder.build();
}
 
Example #22
Source File: BaseCoreFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void buildSessionFactory(Consumer<Configuration> configurationAdapter) {
  // for now, build the configuration to get all the property settings
  configuration = constructAndConfigureConfiguration();
  if ( configurationAdapter != null ) {
    configurationAdapter.accept(configuration);
  }
  BootstrapServiceRegistry bootRegistry = buildBootstrapServiceRegistry();
  serviceRegistry = buildServiceRegistry( bootRegistry, configuration );
  // this is done here because Configuration does not currently support 4.0 xsd
  afterConstructAndConfigureConfiguration( configuration );
  sessionFactory = ( SessionFactoryImplementor ) configuration.buildSessionFactory( serviceRegistry );
  afterSessionFactoryBuilt();
}
 
Example #23
Source File: ReactiveServiceRegistryBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Intended for use exclusively from Quarkus boot-strapping, or extensions of
 * this class which need to override the standard ServiceInitiator list.
 * Consider this an SPI.
 */
protected ReactiveServiceRegistryBuilder(
        BootstrapServiceRegistry bootstrapServiceRegistry,
        Map settings,
        LoadedConfig loadedConfig,
        @SuppressWarnings("rawtypes")
        List<StandardServiceInitiator> initiators) {
    this.bootstrapServiceRegistry = bootstrapServiceRegistry;
    this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
    this.settings = settings;
    this.aggregatedCfgXml = loadedConfig;
    this.initiators = initiators;
}
 
Example #24
Source File: ReactiveServiceRegistryBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a builder with the specified bootstrap services.
 *
 * @param bootstrapServiceRegistry Provided bootstrap registry to use.
 */
public ReactiveServiceRegistryBuilder(
        BootstrapServiceRegistry bootstrapServiceRegistry,
        LoadedConfig loadedConfigBaseline) {
    this.settings = Environment.getProperties();
    this.bootstrapServiceRegistry = bootstrapServiceRegistry;
    this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
    this.aggregatedCfgXml = loadedConfigBaseline;
    this.initiators = defaultReactiveInitiatorList();
}
 
Example #25
Source File: FastBootMetadataBuilder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public FastBootMetadataBuilder(final PersistenceUnitDescriptor persistenceUnit, Scanner scanner,
        Collection<Class<? extends Integrator>> additionalIntegrators, PreGeneratedProxies preGeneratedProxies,
        MultiTenancyStrategy strategy) {
    this.persistenceUnit = persistenceUnit;
    this.additionalIntegrators = additionalIntegrators;
    this.preGeneratedProxies = preGeneratedProxies;
    final ClassLoaderService providedClassLoaderService = FlatClassLoaderService.INSTANCE;

    // Copying semantics from: new EntityManagerFactoryBuilderImpl( unit,
    // integration, instance );
    // Except we remove support for several legacy features and XML binding
    final ClassLoader providedClassLoader = null;

    LogHelper.logPersistenceUnitInformation(persistenceUnit);

    // Build the boot-strap service registry, which mainly handles class loader
    // interactions
    final BootstrapServiceRegistry bsr = buildBootstrapServiceRegistry(providedClassLoaderService);

    // merge configuration sources and build the "standard" service registry
    final RecordableBootstrap ssrBuilder = new RecordableBootstrap(bsr);

    final MergedSettings mergedSettings = mergeSettings(persistenceUnit);
    this.buildTimeSettings = new BuildTimeSettings(mergedSettings.getConfigurationValues());

    // Build the "standard" service registry
    ssrBuilder.applySettings(buildTimeSettings.getSettings());
    this.standardServiceRegistry = ssrBuilder.build();
    registerIdentifierGenerators(standardServiceRegistry);

    this.providedServices = ssrBuilder.getProvidedServices();

    /**
     * This is required to properly integrate Hibernate Envers.
     *
     * The EnversService requires multiple steps to be properly built, the most important ones are:
     *
     * 1. The EnversServiceContributor contributes the EnversServiceInitiator to the RecordableBootstrap.
     * 2. After RecordableBootstrap builds a StandardServiceRegistry, the first time the EnversService is
     * requested, it is created by the initiator and configured by the registry.
     * 3. The MetadataBuildingProcess completes by calling the AdditionalJaxbMappingProducer which
     * initializes the EnversService and produces some additional mapping documents.
     * 4. After that point the EnversService appears to be fully functional.
     *
     * The following trick uses the aforementioned steps to setup the EnversService and then turns it into
     * a ProvidedService so that it is not necessary to repeat all these complex steps during the reactivation
     * of the destroyed service registry in PreconfiguredServiceRegistryBuilder.
     *
     */
    for (Class<? extends Service> postBuildProvidedService : ssrBuilder.getPostBuildProvidedServices()) {
        providedServices.add(new ProvidedService(postBuildProvidedService,
                standardServiceRegistry.getService(postBuildProvidedService)));
    }

    final MetadataSources metadataSources = new MetadataSources(bsr);
    addPUManagedClassNamesToMetadataSources(persistenceUnit, metadataSources);

    this.metamodelBuilder = (MetadataBuilderImplementor) metadataSources
            .getMetadataBuilder(standardServiceRegistry);
    if (scanner != null) {
        this.metamodelBuilder.applyScanner(scanner);
    }
    populate(metamodelBuilder, mergedSettings.cacheRegionDefinitions, standardServiceRegistry);

    this.managedResources = MetadataBuildingProcess.prepare(metadataSources,
            metamodelBuilder.getBootstrapContext());

    applyMetadataBuilderContributor();

    // BVAL integration:
    this.validatorFactory = withValidatorFactory(
            buildTimeSettings.get(org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY));

    // Unable to automatically handle:
    // AvailableSettings.ENHANCER_ENABLE_DIRTY_TRACKING,
    // AvailableSettings.ENHANCER_ENABLE_LAZY_INITIALIZATION,
    // AvailableSettings.ENHANCER_ENABLE_ASSOCIATION_MANAGEMENT

    // for the time being we want to revoke access to the temp ClassLoader if one
    // was passed
    metamodelBuilder.applyTempClassLoader(null);

    if (strategy != null && strategy != MultiTenancyStrategy.NONE) {
        ssrBuilder.addService(MultiTenantConnectionProvider.class, new HibernateMultiTenantConnectionProvider());
    }
    this.multiTenancyStrategy = strategy;

}
 
Example #26
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
private SessionFactory newSessionFactory() {
    final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
        .enableAutoClose();

    Integrator integrator = integrator();
    if (integrator != null) {
        bsrb.applyIntegrator( integrator );
    }

    final BootstrapServiceRegistry bsr = bsrb.build();

    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr)
        .applySettings(properties())
        .build();

    final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    for (Class annotatedClass : entities()) {
        metadataSources.addAnnotatedClass(annotatedClass);
    }

    String[] packages = packages();
    if (packages != null) {
        for (String annotatedPackage : packages) {
            metadataSources.addPackage(annotatedPackage);
        }
    }

    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            metadataSources.addResource(resource);
        }
    }

    final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
    .enableNewIdentifierGeneratorSupport(true)
    .applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        additionalTypes.stream().forEach(type -> {
            metadataBuilder.applyTypes((typeContributions, sr) -> {
                if(type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType ){
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }

    additionalMetadata(metadataBuilder);

    MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if(interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}
 
Example #27
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
private SessionFactory newSessionFactory() {
    final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
            .enableAutoClose();

    Integrator integrator = integrator();
    if (integrator != null) {
        bsrb.applyIntegrator(integrator);
    }

    final BootstrapServiceRegistry bsr = bsrb.build();

    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr)
            .applySettings(properties())
            .build();

    final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    for (Class annotatedClass : entities()) {
        metadataSources.addAnnotatedClass(annotatedClass);
    }

    String[] packages = packages();
    if (packages != null) {
        for (String annotatedPackage : packages) {
            metadataSources.addPackage(annotatedPackage);
        }
    }

    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            metadataSources.addResource(resource);
        }
    }

    final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
    metadataBuilder.enableNewIdentifierGeneratorSupport(true);
    metadataBuilder.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

    MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}
 
Example #28
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
private SessionFactory newSessionFactory() {
    final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
            .enableAutoClose();

    Integrator integrator = integrator();
    if (integrator != null) {
        bsrb.applyIntegrator(integrator);
    }

    final BootstrapServiceRegistry bsr = bsrb.build();

    final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr)
            .applySettings(properties())
            .build();

    final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    for (Class annotatedClass : entities()) {
        metadataSources.addAnnotatedClass(annotatedClass);
    }

    String[] packages = packages();
    if (packages != null) {
        for (String annotatedPackage : packages) {
            metadataSources.addPackage(annotatedPackage);
        }
    }

    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            metadataSources.addResource(resource);
        }
    }

    final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
    metadataBuilder.enableNewIdentifierGeneratorSupport(true);
    metadataBuilder.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        additionalTypes.stream().forEach(type -> {
            metadataBuilder.applyTypes((typeContributions, serviceRegistry1) -> {
                if(type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType ){
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }

    MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}
 
Example #29
Source File: ConfigLoader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ConfigLoader(BootstrapServiceRegistry bootstrapServiceRegistry) {
	this.bootstrapServiceRegistry = bootstrapServiceRegistry;
}
 
Example #30
Source File: MetadataSources.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected static boolean isExpectedServiceRegistryType(ServiceRegistry serviceRegistry) {
	return BootstrapServiceRegistry.class.isInstance( serviceRegistry )
			|| StandardServiceRegistry.class.isInstance( serviceRegistry );
}