Java Code Examples for org.hibernate.service.ServiceRegistry#getService()

The following examples show how to use org.hibernate.service.ServiceRegistry#getService() . 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: Helper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static DatabaseInformation buildDatabaseInformation(
		ServiceRegistry serviceRegistry,
		DdlTransactionIsolator ddlTransactionIsolator,
		Namespace.Name defaultNamespace) {
	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	try {
		return new DatabaseInformationImpl(
				serviceRegistry,
				jdbcEnvironment,
				ddlTransactionIsolator,
				defaultNamespace
		);
	}
	catch (SQLException e) {
		throw jdbcEnvironment.getSqlExceptionHelper().convert( e, "Unable to build DatabaseInformation" );
	}
}
 
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: MultipleHiLoPerTableGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({"StatementWithEmptyBody", "deprecation"})
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	returnClass = type.getReturnedClass();

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

	qualifiedTableName = determineGeneratorTableName( params, jdbcEnvironment );

	segmentColumnName = determineSegmentColumnName( params, jdbcEnvironment );
	keySize = ConfigurationHelper.getInt( PK_LENGTH_NAME, params, DEFAULT_PK_LENGTH );
	segmentName = ConfigurationHelper.getString( PK_VALUE_NAME, params, params.getProperty( TABLE ) );

	valueColumnName = determineValueColumnName( params, jdbcEnvironment );

	//hilo config
	maxLo = ConfigurationHelper.getInt( MAX_LO, params, Short.MAX_VALUE );

	if ( maxLo >= 1 ) {
		hiloOptimizer = new LegacyHiLoAlgorithmOptimizer( returnClass, maxLo );
	}
}
 
Example 4
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 5
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 6
Source File: SchemaCreatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SchemaCreatorImpl(ServiceRegistry serviceRegistry, SchemaFilter schemaFilter) {
	SchemaManagementTool smt = serviceRegistry.getService( SchemaManagementTool.class );
	if ( smt == null || !HibernateSchemaManagementTool.class.isInstance( smt ) ) {
		smt = new HibernateSchemaManagementTool();
		( (HibernateSchemaManagementTool) smt ).injectServices( (ServiceRegistryImplementor) serviceRegistry );
	}

	this.tool = (HibernateSchemaManagementTool) smt;
	this.schemaFilter = schemaFilter;
}
 
Example 7
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 8
Source File: HibernateSchemaManagementTool.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public JdbcContextBuilder(ServiceRegistry serviceRegistry) {
	this.serviceRegistry = serviceRegistry;
	final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
	this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
	this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();

	this.dialect = jdbcServices.getJdbcEnvironment().getDialect();
	this.jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess();
}
 
Example 9
Source File: SchemaDropperImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SchemaDropperImpl(ServiceRegistry serviceRegistry, SchemaFilter schemaFilter) {
	SchemaManagementTool smt = serviceRegistry.getService( SchemaManagementTool.class );
	if ( smt == null || !HibernateSchemaManagementTool.class.isInstance( smt ) ) {
		smt = new HibernateSchemaManagementTool();
		( (HibernateSchemaManagementTool) smt ).injectServices( (ServiceRegistryImplementor) serviceRegistry );
	}

	this.tool = (HibernateSchemaManagementTool) smt;
	this.schemaFilter = schemaFilter;
}
 
Example 10
Source File: SchemaDropperImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public JdbcContextDelayedDropImpl(ServiceRegistry serviceRegistry) {
	this.serviceRegistry = serviceRegistry;
	this.jdbcServices = serviceRegistry.getService( JdbcServices.class );
	this.jdbcConnectionAccess = jdbcServices.getBootstrapJdbcConnectionAccess();
	if ( jdbcConnectionAccess == null ) {
		// todo : log or error?
		throw new SchemaManagementException(
				"Could not build JDBC Connection context to drop schema on SessionFactory close"
		);
	}
}
 
Example 11
Source File: SequenceStyleGenerator.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 {
	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	final Dialect dialect = jdbcEnvironment.getDialect();

	this.identifierType = type;
	boolean forceTableUse = ConfigurationHelper.getBoolean( FORCE_TBL_PARAM, params, false );

	final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment, serviceRegistry );

	final int initialValue = determineInitialValue( params );
	int incrementSize = determineIncrementSize( params );

	final String optimizationStrategy = determineOptimizationStrategy( params, incrementSize );
	incrementSize = determineAdjustedIncrementSize( optimizationStrategy, incrementSize );

	if ( dialect.supportsSequences() && !forceTableUse ) {
		if ( !dialect.supportsPooledSequences() && OptimizerFactory.isPooledOptimizer( optimizationStrategy ) ) {
			forceTableUse = true;
			LOG.forcingTableUse();
		}
	}

	this.databaseStructure = buildDatabaseStructure(
			type,
			params,
			jdbcEnvironment,
			forceTableUse,
			sequenceName,
			initialValue,
			incrementSize
	);
	this.optimizer = OptimizerFactory.buildOptimizer(
			optimizationStrategy,
			identifierType.getReturnedClass(),
			incrementSize,
			ConfigurationHelper.getInt( INITIAL_PARAM, params, -1 )
	);
	this.databaseStructure.prepare( optimizer );
}
 
Example 12
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 13
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 14
Source File: Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void resolveLegacyLimitHandlerBehavior(ServiceRegistry serviceRegistry) {
	// HHH-11194
	// Temporary solution to set whether legacy limit handler behavior should be used.
	final ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
	legacyLimitHandlerBehavior = configurationService.getSetting(
			AvailableSettings.USE_LEGACY_LIMIT_HANDLERS,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example 15
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 16
Source File: DefaultReactiveMergeEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
private EntityCopyObserver createEntityCopyObserver(SessionFactoryImplementor sessionFactory) {
	final ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
	final EntityCopyObserverFactory configurationService = serviceRegistry.getService( EntityCopyObserverFactory.class );
	return configurationService.createEntityCopyObserver();
}
 
Example 17
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void doExecution(
		Action action,
		boolean needsJdbc,
		Metadata metadata,
		ServiceRegistry serviceRegistry,
		TargetDescriptor targetDescriptor) {
	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );

	config.put( AvailableSettings.HBM2DDL_DELIMITER, delimiter );
	config.put( AvailableSettings.FORMAT_SQL, format );
	config.put( AvailableSettings.HBM2DDL_IMPORT_FILES, importFiles );

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

	final ExceptionHandler exceptionHandler = haltOnError
			? ExceptionHandlerHaltImpl.INSTANCE
			: new ExceptionHandlerCollectingImpl();
	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			exceptionHandler
	);

	final SourceDescriptor sourceDescriptor = new SourceDescriptor() {
		@Override
		public SourceType getSourceType() {
			return SourceType.METADATA;
		}

		@Override
		public ScriptSourceInput getScriptSourceInput() {
			return null;
		}
	};

	try {
		if ( action.doDrop() ) {
			tool.getSchemaDropper( config ).doDrop(
					metadata,
					executionOptions,
					sourceDescriptor,
					targetDescriptor
			);
		}

		if ( action.doCreate() ) {
			tool.getSchemaCreator( config ).doCreation(
					metadata,
					executionOptions,
					sourceDescriptor,
					targetDescriptor
			);
		}
	}
	finally {
		if ( exceptionHandler instanceof ExceptionHandlerCollectingImpl ) {
			exceptions.addAll( ( (ExceptionHandlerCollectingImpl) exceptionHandler ).getExceptions() );
		}
	}
}
 
Example 18
Source File: ClassLoaderAccessImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ClassLoaderAccessImpl(ClassLoader tempClassLoader, ServiceRegistry serviceRegistry) {
	this( tempClassLoader, serviceRegistry.getService( ClassLoaderService.class ) );
}
 
Example 19
Source File: SchemaManagementToolCoordinator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void process(
		final Metadata metadata,
		final ServiceRegistry serviceRegistry,
		final Map configurationValues,
		DelayedDropRegistry delayedDropRegistry) {
	final ActionGrouping actions = ActionGrouping.interpret( configurationValues );

	if ( actions.getDatabaseAction() == Action.NONE && actions.getScriptAction() == Action.NONE ) {
		// no actions specified
		log.debug( "No actions specified; doing nothing" );
		return;
	}

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

	boolean haltOnError = configService.getSetting( AvailableSettings.HBM2DDL_HALT_ON_ERROR, Boolean.class, false);

	final ExecutionOptions executionOptions = buildExecutionOptions(
			configurationValues,
			haltOnError ? ExceptionHandlerHaltImpl.INSTANCE :
					ExceptionHandlerLoggedImpl.INSTANCE
	);

	performScriptAction( actions.getScriptAction(), metadata, tool, serviceRegistry, executionOptions );
	performDatabaseAction( actions.getDatabaseAction(), metadata, tool, serviceRegistry, executionOptions );

	if ( actions.getDatabaseAction() == Action.CREATE_DROP ) {
		//noinspection unchecked
		delayedDropRegistry.registerOnCloseAction(
				tool.getSchemaDropper( configurationValues ).buildDelayedAction(
						metadata,
						executionOptions,
						buildDatabaseTargetDescriptor(
								configurationValues,
								DropSettingSelector.INSTANCE,
								serviceRegistry
						)
				)
		);
	}
}
 
Example 20
Source File: ScanningCoordinator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void applyScanResultsToManagedResources(
		ManagedResourcesImpl managedResources,
		ScanResult scanResult,
		BootstrapContext bootstrapContext,
		XmlMappingBinderAccess xmlMappingBinderAccess) {

	final ScanEnvironment scanEnvironment = bootstrapContext.getScanEnvironment();
	final ServiceRegistry serviceRegistry = bootstrapContext.getServiceRegistry();
	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );


	// mapping files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final Set<String> nonLocatedMappingFileNames = new HashSet<String>();
	final List<String> explicitMappingFileNames = scanEnvironment.getExplicitlyListedMappingFiles();
	if ( explicitMappingFileNames != null ) {
		nonLocatedMappingFileNames.addAll( explicitMappingFileNames );
	}

	for ( MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles() ) {
		managedResources.addXmlBinding( xmlMappingBinderAccess.bind( mappingFileDescriptor.getStreamAccess() ) );
		nonLocatedMappingFileNames.remove( mappingFileDescriptor.getName() );
	}

	for ( String name : nonLocatedMappingFileNames ) {
		final URL url = classLoaderService.locateResource( name );
		if ( url == null ) {
			throw new MappingException(
					"Unable to resolve explicitly named mapping-file : " + name,
					new Origin( SourceType.RESOURCE, name )
			);
		}
		final UrlInputStreamAccess inputStreamAccess = new UrlInputStreamAccess( url );
		managedResources.addXmlBinding( xmlMappingBinderAccess.bind( inputStreamAccess ) );
	}


	// classes and packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	final List<String> unresolvedListedClassNames = scanEnvironment.getExplicitlyListedClassNames() == null
			? new ArrayList<String>()
			: new ArrayList<String>( scanEnvironment.getExplicitlyListedClassNames() );

	for ( ClassDescriptor classDescriptor : scanResult.getLocatedClasses() ) {
		if ( classDescriptor.getCategorization() == ClassDescriptor.Categorization.CONVERTER ) {
			// converter classes are safe to load because we never enhance them,
			// and notice we use the ClassLoaderService specifically, not the temp ClassLoader (if any)
			managedResources.addAttributeConverterDefinition(
					AttributeConverterDefinition.from(
							classLoaderService.<AttributeConverter>classForName( classDescriptor.getName() )
					)
			);
		}
		else if ( classDescriptor.getCategorization() == ClassDescriptor.Categorization.MODEL ) {
			managedResources.addAnnotatedClassName( classDescriptor.getName() );
		}
		unresolvedListedClassNames.remove( classDescriptor.getName() );
	}

	// IMPL NOTE : "explicitlyListedClassNames" can contain class or package names...
	for ( PackageDescriptor packageDescriptor : scanResult.getLocatedPackages() ) {
		managedResources.addAnnotatedPackageName( packageDescriptor.getName() );
		unresolvedListedClassNames.remove( packageDescriptor.getName() );
	}

	for ( String unresolvedListedClassName : unresolvedListedClassNames ) {
		// because the explicit list can contain either class names or package names
		// we need to check for both here...

		// First, try it as a class name
		final String classFileName = unresolvedListedClassName.replace( '.', '/' ) + ".class";
		final URL classFileUrl = classLoaderService.locateResource( classFileName );
		if ( classFileUrl != null ) {
			managedResources.addAnnotatedClassName( unresolvedListedClassName );
			continue;
		}

		// Then, try it as a package name
		final String packageInfoFileName = unresolvedListedClassName.replace( '.', '/' ) + "/package-info.class";
		final URL packageInfoFileUrl = classLoaderService.locateResource( packageInfoFileName );
		if ( packageInfoFileUrl != null ) {
			managedResources.addAnnotatedPackageName( unresolvedListedClassName );
			continue;
		}

		log.debugf(
				"Unable to resolve class [%s] named in persistence unit [%s]",
				unresolvedListedClassName,
				scanEnvironment.getRootUrl()
		);
	}
}