# Services

## What are services?

Services are classes that provide Hibernate with pluggable implementations of various types of functionality. Specifically they are implementations of certain service contract interfaces. The interface is known as the service role; the implementation class is know as the service implementation. Generally speaking, users can plug in alternate implementations of all standard service roles (overriding); they can also define additional services beyond the base set of service roles (extending).

## Service contracts

The basic requirement for a service is to implement the marker interface org.hibernate.service.Service. Hibernate uses this internally for some basic type safety.

Optionally, the service can also implement the org.hibernate.service.spi.Startable and org.hibernate.service.spi.Stoppable interfaces to receive notifications of being started and stopped. Another optional service contract is org.hibernate.service.spi.Manageable which marks the service as manageable in JMX provided the JMX integration is enabled.

## Service dependencies

Services are allowed to declare dependencies on other services using either of 2 approaches.

### @org.hibernate.service.spi.InjectService

Any method on the service implementation class accepting a single parameter and annotated with @InjectService is considered requesting injection of another service.

By default the type of the method parameter is expected to be the service role to be injected. If the parameter type is different than the service role, the serviceRole attribute of the InjectService should be used to explicitly name the role.

By default injected services are considered required, that is the start up will fail if a named dependent service is missing. If the service to be injected is optional, the required attribute of the InjectService should be declared as `false` (default is `true`).

### org.hibernate.service.spi.ServiceRegistryAwareService

The second approach is a pull approach where the service implements the optional service interface org.hibernate.service.spi.ServiceRegistryAwareService which declares a single injectServices method. During startup, Hibernate will inject the org.hibernate.service.ServiceRegistry itself into services which implement this interface. The service can then use the ServiceRegistry reference to locate any additional services it needs.

## ServiceRegistry

The central service API, aside from the services themselves, is the org.hibernate.service.ServiceRegistry interface. The main purpose of a service registry is to hold, manage and provide access to services.

Service registries are hierarchical. Services in one registry can depend on and utilize services in that same registry as well as any parent registries.

Use org.hibernate.service.ServiceRegistryBuilder to build a org.hibernate.service.ServiceRegistry instance.

## Standard services

### org.hibernate.engine.jdbc.batch.spi.BatchBuilder

Notes

  Defines strategy for how Hibernate manages JDBC statement batching

Initiator

  org.hibernate.engine.jdbc.batch.internal.BatchBuilderInitiator

Implementations

  org.hibernate.engine.jdbc.batch.internal.BatchBuilderImpl

### org.hibernate.service.config.spi.ConfigurationService

Notes

  Provides access to the configuration settings, combining those explicitly provided as well as those contributed by any registered org.hibernate.integrator.spi.Integrator implementations

Initiator

  org.hibernate.service.config.internal.ConfigurationServiceInitiator

Implementations

  org.hibernate.service.config.internal.ConfigurationServiceImpl

### org.hibernate.service.jdbc.connections.spi.ConnectionProvider

Notes

  Defines the means in which Hibernate can obtain and release java.sql.Connection instances for its use.

Initiator

  org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator

Implementations

  - org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider - provides connection pooling based on integration with the C3P0 connection pooling library

  - org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl - provides connection managed delegated to a javax.sql.DataSource

  - org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - provides rudimentary connection pooling based on simple custom pool. Note intended production use!

  - org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider - provides connection pooling based on integration with the proxool connection pooling library

  - org.hibernate.service.jdbc.connections.internal.UserSuppliedConnectionProviderImpl - Provides no connection support. Indicates the user will supply connections to Hibernate directly. Not recommended for use.

### org.hibernate.service.jdbc.dialect.spi.DialectFactory

Notes

  Contract for Hibernate to obtain org.hibernate.dialect.Dialect instance to use. This is either explicitly defined by the hibernate.dialect property or determined by the service which is a delegate to this service.

Initiator

  org.hibernate.service.jdbc.dialect.internal.DialectFactoryInitiator

Implementations

  org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl

### org.hibernate.service.jdbc.dialect.spi.DialectResolver

Notes

  Provides resolution of org.hibernate.dialect.Dialect to use based on information extracted from JDBC metadata.

  The standard resolver implementation acts as a chain, delegating to a series of individual resolvers. The standard Hibernate resolution behavior is contained in org.hibernate.service.jdbc.dialect.internal.StandardDialectResolver. org.hibernate.service.jdbc.dialect.internal.DialectResolverInitiator also consults with the hibernate.dialect_resolvers setting for any custom resolvers.

Initiator

  org.hibernate.service.jdbc.dialect.internal.DialectResolverInitiator

Implementations

  org.hibernate.service.jdbc.dialect.internal.DialectResolverSet

### org.hibernate.engine.jdbc.spi.JdbcServices

Notes

  Special type of service that aggregates together a number of other services and provides a higher-level set of functionality.

Initiator

  org.hibernate.engine.jdbc.internal.JdbcServicesInitiator

Implementations

  org.hibernate.engine.jdbc.internal.JdbcServicesImpl

### org.hibernate.service.jmx.spi.JmxService

Notes

  Provides simplified access to JMX related features needed by Hibernate.

Initiator

  org.hibernate.service.jmx.internal.JmxServiceInitiator

Implementations

  - org.hibernate.service.jmx.internal.DisabledJmxServiceImpl - A no-op implementation when JMX functionality is disabled.

  - org.hibernate.service.jmx.internal.JmxServiceImpl - Standard implementation of JMX handling

### org.hibernate.service.jndi.spi.JndiService

Notes

  Provides simplified access to JNDI related features needed by Hibernate.

Initiator

  org.hibernate.service.jndi.internal.JndiServiceInitiator

Implementations

  org.hibernate.service.jndi.internal.JndiServiceImpl

### org.hibernate.service.jta.platform.spi.JtaPlatform

Notes

  Provides an abstraction from the underlying JTA platform when JTA features are used.

Initiator

  org.hibernate.service.jta.platform.internal.JtaPlatformInitiator

  JtaPlatformInitiator provides mapping against the legacy, now-deprecated org.hibernate.transaction.TransactionManagerLookup names internally for the Hibernate-provided org.hibernate.transaction.TransactionManagerLookup implementations.

Implementations

  - org.hibernate.service.jta.platform.internal.BitronixJtaPlatform - Integration with the Bitronix stand-alone transaction manager.

  - org.hibernate.service.jta.platform.internal.BorlandEnterpriseServerJtaPlatform - Integration with the transaction manager as deployed within a Borland Enterprise Server

  - org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform - Integration with the transaction manager as deployed within a JBoss Application Server

  - org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform - Integration with the JBoss Transactions stand-alone transaction manager

  - org.hibernate.service.jta.platform.internal.JOTMJtaPlatform - Integration with the JOTM stand-alone transaction manager

  - org.hibernate.service.jta.platform.internal.JOnASJtaPlatform - Integration with the JOnAS transaction manager.

  - org.hibernate.service.jta.platform.internal.JRun4JtaPlatform - Integration with the transaction manager as deployed in a JRun 4 application server.

  - org.hibernate.service.jta.platform.internal.NoJtaPlatform - No-op version when no JTA set up is configured

  - org.hibernate.service.jta.platform.internal.OC4JJtaPlatform - Integration with transaction manager as deployed in an OC4J (Oracle) application server.

  - org.hibernate.service.jta.platform.internal.OrionJtaPlatform - Integration with transaction manager as deployed in an Orion application server.

  - org.hibernate.service.jta.platform.internal.ResinJtaPlatform - Integration with transaction manager as deployed in a Resin application server.

  - org.hibernate.service.jta.platform.internal.SunOneJtaPlatform - Integration with transaction manager as deployed in a Sun ONE (7 and above) application server.

  - org.hibernate.service.jta.platform.internal.TransactionManagerLookupBridge - Provides a bridge to legacy (and deprecated) org.hibernate.transaction.TransactionManagerLookup implementations

  - org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform - Integration with transaction manager as deployed in a WebSphere Application Server (6 and above).

  - org.hibernate.service.jta.platform.internal.WebSphereJtaPlatform - Integration with transaction manager as deployed in a WebSphere Application Server (4, 5.0 and 5.1).

  - org.hibernate.service.jta.platform.internal.WeblogicJtaPlatform - Integration with transaction manager as deployed in a Weblogic application server.

### org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider

Notes

  A variation of providing access to JDBC connections in multi-tenant environments.

Initiator

  N/A

Implementations

  Intended that users provide appropriate implementation if needed.

### org.hibernate.persister.spi.PersisterClassResolver

Notes

  Contract for determining the appropriate org.hibernate.persister.entity.EntityPersister or org.hibernate.persister.collection.CollectionPersister implementation class to use given an entity or collection mapping.

Initiator

  org.hibernate.persister.internal.PersisterClassResolverInitiator

Implementations

  org.hibernate.persister.internal.StandardPersisterClassResolver

### org.hibernate.persister.spi.PersisterFactory

Notes

  Factory for creating org.hibernate.persister.entity.EntityPersister and org.hibernate.persister.collection.CollectionPersister instances.

Initiator

  org.hibernate.persister.internal.PersisterFactoryInitiator

Implementations

  org.hibernate.persister.internal.PersisterFactoryImpl

### org.hibernate.cache.spi.RegionFactory

Notes

  Integration point for Hibernate's second level cache support.

Initiator

  org.hibernate.cache.internal.RegionFactoryInitiator

Implementations

  - org.hibernate.cache.ehcache.EhCacheRegionFactory

  - org.hibernate.cache.infinispan.InfinispanRegionFactory

  - org.hibernate.cache.infinispan.JndiInfinispanRegionFactory

  - org.hibernate.cache.internal.NoCachingRegionFactory

  - org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

### org.hibernate.service.spi.SessionFactoryServiceRegistryFactory

Notes

  Factory for creating org.hibernate.service.spi.SessionFactoryServiceRegistry instances which acts as a specialized org.hibernate.service.ServiceRegistry for org.hibernate.SessionFactory scoped services. See for more details.

Initiator

  org.hibernate.service.internal.SessionFactoryServiceRegistryFactoryInitiator

Implementations

  org.hibernate.service.internal.SessionFactoryServiceRegistryFactoryImpl

### org.hibernate.stat.Statistics

Notes

  Contract for exposing collected statistics. The statistics are collected through the org.hibernate.stat.spi.StatisticsImplementor contract.

Initiator

  org.hibernate.stat.internal.StatisticsInitiator

  Defines a hibernate.stats.factory setting to allow configuring the org.hibernate.stat.spi.StatisticsFactory to use internally when building the actual org.hibernate.stat.Statistics instance.

Implementations

  org.hibernate.stat.internal.ConcurrentStatisticsImpl

  The default org.hibernate.stat.spi.StatisticsFactory implementation builds a org.hibernate.stat.internal.ConcurrentStatisticsImpl instance.

### org.hibernate.engine.transaction.spi.TransactionFactory

Notes

  Strategy defining how Hibernate's org.hibernate.Transaction API maps to the underlying transaction approach.

Initiator

  org.hibernate.stat.internal.StatisticsInitiator

  Defines a hibernate.stats.factory setting to allow configuring the org.hibernate.stat.spi.StatisticsFactory to use internally when building the actual org.hibernate.stat.Statistics instance.

Implementations

  - org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory - A JTA-based strategy in which Hibernate is not controlling the transactions. An important distinction here is that interaction with the underlying JTA implementation is done through the javax.transaction.TransactionManager

  - org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory - A non-JTA strategy in which the transactions are managed using the JDBC java.sql.Connection

  - org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory - A JTA-based strategy in which Hibernate *may* be controlling the transactions. An important distinction here is that interaction with the underlying JTA implementation is done through the javax.transaction.UserTransaction

### org.hibernate.tool.hbm2ddl.ImportSqlCommandExtractor

Notes

  Contract for extracting statements from `import.sql` scripts.

Initiator

  org.hibernate.tool.hbm2ddl.ImportSqlCommandExtractorInitiator

Implementations

  - org.hibernate.tool.hbm2ddl.SingleLineSqlCommandExtractor treats each line as a complete SQL statement. Comment lines shall start with `--`, `//` or `/*` character sequence.

  - org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor supports instructions/comments and quoted strings spread over multiple lines. Each statement must end with semicolon.

## Custom services

Once a org.hibernate.service.ServiceRegistry is built it is considered immutable; the services themselves might accept re-configuration, but immutability here means adding/replacing services. So another role provided by the org.hibernate.service.ServiceRegistryBuilder is to allow tweaking of the services that will be contained in the org.hibernate.service.ServiceRegistry generated from it.

There are 2 means to tell a org.hibernate.service.ServiceRegistryBuilder about custom services.

- Implement a org.hibernate.service.spi.BasicServiceInitiator class to control on-demand construction of the service class and add it to the org.hibernate.service.ServiceRegistryBuilder via its addInitiator method.

- Just instantiate the service class and add it to the org.hibernate.service.ServiceRegistryBuilder via its addService method.

Either approach the adding a service approach or the adding an initiator approach are valid for extending a registry (adding new service roles) and overriding services (replacing service implementations).

## Special service registries

### Boot-strap registry

The boot-strap registry holds services that absolutely have to be available for most things to work. The main service here is the which is a perfect example. Even resolving configuration files needs access to class loading services (resource look ups). This is the root registry (no parent) in normal use.

Instances of boot-strap registries are built using the org.hibernate.service.BootstrapServiceRegistryBuilder class.

Using BootstrapServiceRegistryBuilder

#### Bootstrap registry services

##### org.hibernate.service.classloading.spi.ClassLoaderService

Hibernate needs to interact with ClassLoaders. However, the manner in which Hibernate (or any library) should interact with ClassLoaders varies based on the runtime environment which is hosting the application. Application servers, OSGi containers, and other modular class loading systems impose very specific class-loading requirements. This service is provides Hibernate an abstraction from this environmental complexity. And just as importantly, it does so in a single-swappable-component manner.

In terms of interacting with a ClassLoader, Hibernate needs the following capabilities:

- the ability to locate application classes

- the ability to locate integration classes

- the ability to locate resources (properties files, xml files, etc)

- the ability to load java.util.ServiceLoader

Currently, the ability to load application classes and the ability to load integration classes are combined into a single "load class" capability on the service. That may change in a later release.

##### org.hibernate.integrator.spi.IntegratorService

Applications, add-ons and others all need to integrate with Hibernate which used to require something, usually the application, to coordinate registering the pieces of each integration needed on behalf of each integrator. The intent of this service is to allow those integrators to be discovered and to have them integrate themselves with Hibernate.

This service focuses on the discovery aspect. It leverages the standard Java java.util.ServiceLoader capability provided by the org.hibernate.service.classloading.spi.ClassLoaderService in order to discover implementations of the org.hibernate.integrator.spi.Integrator contract. Integrators would simply define a file named `/META-INF/services/org.hibernate.integrator.spi.Integrator` and make it available on the classpath. java.util.ServiceLoader covers the format of this file in detail, but essentially it list classes by FQN that implement the org.hibernate.integrator.spi.Integrator one per line.

See

### SessionFactory registry

While it is best practice to treat instances of all the registry types as targeting a given org.hibernate.SessionFactory, the instances of services in this group explicitly belong to a single org.hibernate.SessionFactory. The difference is a matter of timing in when they need to be initiated. Generally they need access to the org.hibernate.SessionFactory to be initiated. This special registry is org.hibernate.service.spi.SessionFactoryServiceRegistry

#### org.hibernate.event.service.spi.EventListenerRegistry

Notes

  Service for managing event listeners.

Initiator

  org.hibernate.event.service.internal.EventListenerServiceInitiator

Implementations

  org.hibernate.event.service.internal.EventListenerRegistryImpl

## Using services and registries

Coming soon...

## Integrators

The org.hibernate.integrator.spi.Integrator is intended to provide a simple means for allowing developers to hook into the process of building a functioning SessionFactory. The The org.hibernate.integrator.spi.Integrator interface defines 2 methods of interest: integrate allows us to hook into the building process; disintegrate allows us to hook into a SessionFactory shutting down.

There is a 3rd method defined on org.hibernate.integrator.spi.Integrator, an overloaded form of integrate accepting a org.hibernate.metamodel.source.MetadataImplementor instead of org.hibernate.cfg.Configuration. This form is intended for use with the new metamodel code scheduled for completion in 5.0

See

In addition to the discovery approach provided by the IntegratorService, applications can manually register Integrator implementations when building the BootstrapServiceRegistry. See

### Integrator use-cases

The main use cases for an org.hibernate.integrator.spi.Integrator right now are registering event listeners and providing services (see org.hibernate.integrator.spi.ServiceContributingIntegrator). With 5.0 we plan on expanding that to allow altering the metamodel describing the mapping between object and relational models.

Registering event listeners