下面列出了怎么用org.hibernate.integrator.spi.Integrator的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Determine the Hibernate {@link MetadataSources} to use.
* <p>Can also be externally called to initialize and pre-populate a {@link MetadataSources}
* instance which is then going to be used for {@link SessionFactory} building.
* @return the MetadataSources to use (never {@code null})
* @since 4.3
* @see LocalSessionFactoryBuilder#LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources)
*/
public MetadataSources getMetadataSources() {
this.metadataSourcesAccessed = true;
if (this.metadataSources == null) {
BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder();
if (this.resourcePatternResolver != null) {
builder = builder.applyClassLoader(this.resourcePatternResolver.getClassLoader());
}
if (this.hibernateIntegrators != null) {
for (Integrator integrator : this.hibernateIntegrators) {
builder = builder.applyIntegrator(integrator);
}
}
this.metadataSources = new MetadataSources(builder.build());
}
return this.metadataSources;
}
/**
* Determine the Hibernate {@link MetadataSources} to use.
* <p>Can also be externally called to initialize and pre-populate a {@link MetadataSources}
* instance which is then going to be used for {@link SessionFactory} building.
* @return the MetadataSources to use (never {@code null})
* @since 4.3
* @see LocalSessionFactoryBuilder#LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources)
*/
public MetadataSources getMetadataSources() {
this.metadataSourcesAccessed = true;
if (this.metadataSources == null) {
BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder();
if (this.resourcePatternResolver != null) {
builder = builder.applyClassLoader(this.resourcePatternResolver.getClassLoader());
}
if (this.hibernateIntegrators != null) {
for (Integrator integrator : this.hibernateIntegrators) {
builder = builder.applyIntegrator(integrator);
}
}
this.metadataSources = new MetadataSources(builder.build());
}
return this.metadataSources;
}
private static Map<String, RecordedState> constructMetadataAdvance(
final List<PersistenceUnitDescriptor> parsedPersistenceXmlDescriptors, Scanner scanner,
Collection<Class<? extends Integrator>> additionalIntegrators,
PreGeneratedProxies proxyClassDefinitions,
MultiTenancyStrategy strategy) {
Map<String, RecordedState> recordedStates = new HashMap<>();
for (PersistenceUnitDescriptor unit : parsedPersistenceXmlDescriptors) {
RecordedState m = createMetadata(unit, scanner, additionalIntegrators, proxyClassDefinitions, strategy);
Object previous = recordedStates.put(unitName(unit), m);
if (previous != null) {
throw new IllegalStateException("Duplicate persistence unit name: " + unit.getName());
}
}
return recordedStates;
}
/**
* Constructs a BootstrapServiceRegistryImpl.
*
* Do not use directly generally speaking. Use {@link org.hibernate.boot.registry.BootstrapServiceRegistryBuilder}
* instead.
*
* @param autoCloseRegistry See discussion on
* {@link org.hibernate.boot.registry.BootstrapServiceRegistryBuilder#disableAutoClose}
* @param classLoaderService The ClassLoaderService to use
* @param providedIntegrators The group of explicitly provided integrators
*
* @see org.hibernate.boot.registry.BootstrapServiceRegistryBuilder
*/
public BootstrapServiceRegistryImpl(
boolean autoCloseRegistry,
ClassLoaderService classLoaderService,
LinkedHashSet<Integrator> providedIntegrators) {
this.autoCloseRegistry = autoCloseRegistry;
this.classLoaderServiceBinding = new ServiceBinding<ClassLoaderService>(
this,
ClassLoaderService.class,
classLoaderService
);
final StrategySelectorImpl strategySelector = new StrategySelectorImpl( classLoaderService );
this.strategySelectorBinding = new ServiceBinding<StrategySelector>(
this,
StrategySelector.class,
strategySelector
);
this.integratorServiceBinding = new ServiceBinding<IntegratorService>(
this,
IntegratorService.class,
new IntegratorServiceImpl( providedIntegrators, classLoaderService )
);
}
protected EntityManagerFactory newEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<String, Object>();
configuration.put(AvailableSettings.INTERCEPTOR, interceptor());
final Integrator integrator = integrator();
if (integrator != null) {
configuration.put(
"hibernate.integrator_provider",
new IntegratorProvider() {
@Override
public List<Integrator> getIntegrators() {
return Collections.singletonList(integrator);
}
}
);
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
);
return entityManagerFactoryBuilder.build();
}
@Before
public void init() {
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
Integrator integrator = integrator();
if (integrator != null) {
configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
}
emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
persistenceUnitInfo,
configuration
);
}
protected EntityManagerFactory newEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();
Interceptor interceptor = interceptor();
if (interceptor != null) {
configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}
Integrator integrator = integrator();
if (integrator != null) {
configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
);
return entityManagerFactoryBuilder.build();
}
@SuppressWarnings("deprecation")
private void applyServiceContributingIntegrators() {
for ( Integrator integrator : bootstrapServiceRegistry.getService( IntegratorService.class )
.getIntegrators() ) {
if (integrator instanceof ServiceContributingIntegrator) {
((ServiceContributingIntegrator) integrator).prepareServices( this );
}
}
}
/**
* @param applicationContext The application context
* @param integrator The {@link Integrator}
* @param entityScanConfiguration The entity scan configuration
*/
@Inject
protected JpaConfiguration(ApplicationContext applicationContext,
@Nullable Integrator integrator,
@Nullable EntityScanConfiguration entityScanConfiguration) {
ClassLoader classLoader = applicationContext.getClassLoader();
BootstrapServiceRegistryBuilder bootstrapServiceRegistryBuilder =
createBootstrapServiceRegistryBuilder(integrator, classLoader);
this.bootstrapServiceRegistry = bootstrapServiceRegistryBuilder.build();
this.entityScanConfiguration = entityScanConfiguration != null ? entityScanConfiguration : new EntityScanConfiguration(applicationContext.getEnvironment());
this.environment = applicationContext.getEnvironment();
this.applicationContext = applicationContext;
}
/**
* Creates the default {@link BootstrapServiceRegistryBuilder}.
*
* @param integrator The integrator to use. Can be null
* @param classLoader The class loade rto use
* @return The BootstrapServiceRegistryBuilder
*/
@SuppressWarnings("WeakerAccess")
protected BootstrapServiceRegistryBuilder createBootstrapServiceRegistryBuilder(
@Nullable Integrator integrator,
ClassLoader classLoader) {
BootstrapServiceRegistryBuilder bootstrapServiceRegistryBuilder = new BootstrapServiceRegistryBuilder();
bootstrapServiceRegistryBuilder.applyClassLoader(classLoader);
if (integrator != null) {
bootstrapServiceRegistryBuilder.applyIntegrator(integrator);
}
return bootstrapServiceRegistryBuilder;
}
public RecordedState(Dialect dialect, PrevalidatedQuarkusMetadata metadata,
BuildTimeSettings settings, Collection<Integrator> integrators,
Collection<ProvidedService> providedServices, IntegrationSettings integrationSettings,
ProxyDefinitions classDefinitions, MultiTenancyStrategy strategy) {
this.dialect = dialect;
this.metadata = metadata;
this.settings = settings;
this.integrators = integrators;
this.providedServices = providedServices;
this.integrationSettings = integrationSettings;
this.proxyClassDefinitions = classDefinitions;
this.multiTenancyStrategy = strategy;
}
public BeanContainerListener initMetadata(List<ParsedPersistenceXmlDescriptor> parsedPersistenceXmlDescriptors,
Scanner scanner, Collection<Class<? extends Integrator>> additionalIntegrators,
PreGeneratedProxies proxyDefinitions, MultiTenancyStrategy strategy) {
return new BeanContainerListener() {
@Override
public void created(BeanContainer beanContainer) {
PersistenceUnitsHolder.initializeJpa(parsedPersistenceXmlDescriptors, scanner, additionalIntegrators,
proxyDefinitions, strategy);
}
};
}
public static RecordedState createMetadata(PersistenceUnitDescriptor unit, Scanner scanner,
Collection<Class<? extends Integrator>> additionalIntegrators, PreGeneratedProxies proxyDefinitions,
MultiTenancyStrategy strategy) {
FastBootMetadataBuilder fastBootMetadataBuilder = new FastBootMetadataBuilder(unit, scanner, additionalIntegrators,
proxyDefinitions, strategy);
return fastBootMetadataBuilder.build();
}
private Collection<Integrator> getIntegrators() {
LinkedHashSet<Integrator> integrators = new LinkedHashSet<>();
integrators.add(new BeanValidationIntegrator());
integrators.add(new CollectionCacheInvalidator());
for (Class<? extends Integrator> integratorClass : additionalIntegrators) {
try {
integrators.add(integratorClass.getConstructor().newInstance());
} catch (Exception e) {
throw new IllegalArgumentException("Unable to instantiate integrator " + integratorClass, e);
}
}
return integrators;
}
@SuppressWarnings("deprecation")
private void applyServiceContributingIntegrators() {
for ( Integrator integrator : bootstrapServiceRegistry.getService( IntegratorService.class )
.getIntegrators() ) {
if ( org.hibernate.integrator.spi.ServiceContributingIntegrator.class.isInstance( integrator ) ) {
org.hibernate.integrator.spi.ServiceContributingIntegrator.class.cast( integrator ).prepareServices(
this );
}
}
}
protected EntityManagerFactory newEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
configuration.put(AvailableSettings.INTERCEPTOR, interceptor());
Integrator integrator = integrator();
if (integrator != null) {
configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
}
final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) {
configuration.put("hibernate.type_contributors", (TypeContributorList) () -> {
List<TypeContributor> typeContributors = new ArrayList<>();
for (Type additionalType : additionalTypes) {
if (additionalType instanceof BasicType) {
typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((BasicType) additionalType));
} else if (additionalType instanceof UserType) {
typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((UserType) additionalType));
} else if (additionalType instanceof CompositeUserType) {
typeContributors.add((typeContributions, serviceRegistry) -> typeContributions.contributeType((CompositeUserType) additionalType));
}
}
return typeContributors;
});
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
);
return entityManagerFactoryBuilder.build();
}
private Metadata getMetadataInternal() {
Metadata metadata = null;
ServiceRegistry bootstrapServiceRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getParentServiceRegistry();
Iterable<Integrator> integrators = bootstrapServiceRegistry.getService(IntegratorService.class).getIntegrators();
for (Integrator integrator : integrators) {
if (integrator instanceof MetadataIntegrator) {
metadata = ((MetadataIntegrator) integrator).getMetadata();
}
}
return metadata;
}
@Override
public List<Integrator> getIntegrators() {
return List.of(
new ClassImportIntegrator(
List.of(
PostDTO.class
)
)
);
}
/**
* @param applicationContext The application context
* @param integrator The {@link Integrator}
*/
protected JpaConfiguration(ApplicationContext applicationContext,
@Nullable Integrator integrator) {
this(applicationContext, integrator, new EntityScanConfiguration(applicationContext.getEnvironment()));
}
@SuppressWarnings("unchecked")
@BuildStep
@Record(STATIC_INIT)
public void build(RecorderContext recorderContext, HibernateOrmRecorder recorder,
Capabilities capabilities,
JpaEntitiesBuildItem domainObjects,
List<NonJpaModelBuildItem> nonJpaModelBuildItems,
List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems,
List<HibernateOrmIntegrationBuildItem> integrations, //Used to make sure ORM integrations are performed before this item
ProxyDefinitionsBuildItem proxyDefinitions,
BuildProducer<FeatureBuildItem> feature,
BuildProducer<BeanContainerListenerBuildItem> beanContainerListener) throws Exception {
feature.produce(new FeatureBuildItem(Feature.HIBERNATE_ORM));
final boolean enableORM = hasEntities(domainObjects, nonJpaModelBuildItems);
final boolean hibernateReactivePresent = capabilities.isPresent(Capability.HIBERNATE_REACTIVE);
//The Hibernate Reactive extension is able to handle registration of PersistenceProviders for both reactive and
//traditional blocking Hibernate, by depending on this module and delegating to this code.
//So when the Hibernate Reactive extension is present, trust that it will register its own PersistenceProvider
//which will be responsible to decide which type of ORM to bootstrap.
//But if the extension is not present, we need to register our own PersistenceProvider - even if the ORM is not enabled!
if (!hibernateReactivePresent) {
recorder.callHibernateFeatureInit(enableORM);
}
if (!enableORM) {
// we can bail out early
return;
}
recorder.enlistPersistenceUnit(domainObjects.getEntityClassNames());
final QuarkusScanner scanner = buildQuarkusScanner(domainObjects);
//now we serialize the XML and class list to bytecode, to remove the need to re-parse the XML on JVM startup
recorderContext.registerNonDefaultConstructor(ParsedPersistenceXmlDescriptor.class.getDeclaredConstructor(URL.class),
(i) -> Collections.singletonList(i.getPersistenceUnitRootUrl()));
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// inspect service files for additional integrators
Collection<Class<? extends Integrator>> integratorClasses = new LinkedHashSet<>();
for (String integratorClassName : ServiceUtil.classNamesNamedIn(classLoader, INTEGRATOR_SERVICE_FILE)) {
integratorClasses.add((Class<? extends Integrator>) recorderContext.classProxy(integratorClassName));
}
List<ParsedPersistenceXmlDescriptor> allDescriptors = new ArrayList<>();
for (PersistenceUnitDescriptorBuildItem pud : persistenceUnitDescriptorBuildItems) {
allDescriptors.add(pud.getDescriptor());
}
beanContainerListener
.produce(new BeanContainerListenerBuildItem(
recorder.initMetadata(allDescriptors, scanner, integratorClasses,
proxyDefinitions.getProxies(), getMultiTenancyStrategy())));
}
public Collection<Integrator> getIntegrators() {
return integrators;
}
@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;
}
public PreconfiguredServiceRegistryBuilder addIntegrator(Integrator integrator) {
integrators.add(integrator);
return this;
}
public MirroringIntegratorService(Collection<Integrator> integrators) {
this.integrators = integrators;
}
@Override
public Iterable<Integrator> getIntegrators() {
return integrators;
}
public QuarkusIntegratorServiceImpl(final ClassLoaderService classLoaderService) {
integrators.addAll(classLoaderService.loadJavaServices(Integrator.class));
}
@Override
public Iterable<Integrator> getIntegrators() {
return integrators;
}
private void addIntegrator(Integrator integrator) {
LOG.debugf( "Adding Integrator [%s].", integrator.getClass().getName() );
integrators.add( integrator );
}
@Override
public Iterable<Integrator> getIntegrators() {
return integrators;
}
/**
* @deprecated Use {@link #applyIntegrator} instead
*/
@Deprecated
public BootstrapServiceRegistryBuilder with(Integrator integrator) {
return applyIntegrator( integrator );
}