Hibernate.orgCommunity Documentation

Chapter 3. Configuration

Table of Contents

3.1. Programmatic configuration
3.2. Obtaining a SessionFactory
3.3. JDBC connections
3.4. Optional configuration properties
3.4.1. SQL Dialects
3.4.2. Outer Join Fetching
3.4.3. Binary Streams
3.4.4. Second-level and query cache
3.4.5. Query Language Substitution
3.4.6. Hibernate statistics
3.5. Logging
3.6. Implementing a Naming Strategy
3.7. Implementing a PersisterClassProvider
3.8. XML configuration file
3.9. Java EE Application Server integration
3.9.1. Transaction strategy configuration
3.9.2. JNDI-bound SessionFactory
3.9.3. Current Session context management with JTA

Hibernate is designed to operate in many different environments and, as such, there is a broad range of configuration parameters. Fortunately, most have sensible default values and Hibernate is distributed with an example hibernate.properties file in etc/ that displays the various options. Simply put the example file in your classpath and customize it to suit your needs.

An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutable org.hibernate.SessionFactory. The mappings are compiled from various XML mapping files.

You can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:

Configuration cfg = new Configuration()

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:

Configuration cfg = new Configuration()

Hibernate will then search for mapping files named /org/hibernate/auction/Item.hbm.xml and /org/hibernate/auction/Bid.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:

Configuration cfg = new Configuration()
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

This is not the only way to pass configuration properties to Hibernate. Some alternative options include:

  1. Pass an instance of java.util.Properties to Configuration.setProperties().

  2. Place a file named hibernate.properties in a root directory of the classpath.

  3. Set System properties using java -Dproperty=value.

  4. Include <property> elements in hibernate.cfg.xml (this is discussed later).

If you want to get started quicklyhibernate.properties is the easiest approach.

The org.hibernate.cfg.Configuration is intended as a startup-time object that will be discarded once a SessionFactory is created.

When all mappings have been parsed by the org.hibernate.cfg.Configuration, the application must obtain a factory for org.hibernate.Session instances. This factory is intended to be shared by all application threads:

SessionFactory sessions = cfg.buildSessionFactory();

Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory. This is useful if you are using more than one database.

It is advisable to have the org.hibernate.SessionFactory create and pool JDBC connections for you. If you take this approach, opening a org.hibernate.Session is as simple as:

Session session = sessions.openSession(); // open a new Session

Once you start a task that requires access to the database, a JDBC connection will be obtained from the pool.

Before you can do this, you first need to pass some JDBC connection properties to Hibernate. All Hibernate property names and semantics are defined on the class org.hibernate.cfg.Environment. The most important settings for JDBC connection configuration are outlined below.

Hibernate will obtain and pool connections using java.sql.DriverManager if you set the following properties:

Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate will use its org.hibernate.connection.C3P0ConnectionProvider for connection pooling if you set hibernate.c3p0.* properties. If you would like to use Proxool, refer to the packaged hibernate.properties and the Hibernate web site for more information.

The following is an example hibernate.properties file for c3p0:

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server javax.sql.Datasource registered in JNDI. You will need to set at least one of the following properties:

Here is an example hibernate.properties file for an application server provided JNDI datasource:

hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
hibernate.transaction.manager_lookup_class = \
hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

JDBC connections obtained from a JNDI datasource will automatically participate in the container-managed transactions of the application server.

Arbitrary connection properties can be given by prepending "hibernate.connection" to the connection property name. For example, you can specify a charSet connection property using hibernate.connection.charSet.

You can define your own plugin strategy for obtaining JDBC connections by implementing the interface org.hibernate.connection.ConnectionProvider, and specifying your custom implementation via the hibernate.connection.provider_class property.

There are a number of other properties that control the behavior of Hibernate at runtime. All are optional and have reasonable default values.


Some of these properties are "system-level" only. System-level properties can be set only via java -Dproperty=value or hibernate.properties. They cannot be set by the other techniques described above.

Table 3.3. Hibernate Configuration Properties

Property namePurpose
hibernate.dialectThe classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.

e.g. full.classname.of.Dialect

In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect implementation based on the JDBC metadata returned by the JDBC driver.

hibernate.show_sqlWrite all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

e.g. true | false

hibernate.format_sqlPretty print the SQL in the log and console.

e.g. true | false

hibernate.default_schemaQualify unqualified table names with the given schema/tablespace in generated SQL.


hibernate.default_catalogQualifies unqualified table names with the given catalog in generated SQL.


hibernate.session_factory_nameThe org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created.

e.g. jndi/composite/name

hibernate.max_fetch_depthSets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.

e.g. recommended values between 0 and 3

hibernate.default_batch_fetch_sizeSets a default size for Hibernate batch fetching of associations.

e.g. recommended values 4, 8, 16

hibernate.default_entity_modeSets a default mode for entity representation for all sessions opened from this SessionFactory, defaults to pojo.

e.g. dynamic-map | pojo

hibernate.order_updatesForces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.

e.g. true | false

hibernate.generate_statisticsIf enabled, Hibernate will collect statistics useful for performance tuning.

e.g. true | false

hibernate.use_identifier_rollbackIf enabled, generated identifier properties will be reset to default values when objects are deleted.

e.g. true | false

hibernate.use_sql_commentsIf turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false.

e.g. true | false

hibernate.id.new_generator_mappingsSetting is relevant when using @GeneratedValue. It indicates whether or not the new IdentifierGenerator implementations are used for javax.persistence.GenerationType.AUTO, javax.persistence.GenerationType.TABLE and javax.persistence.GenerationType.SEQUENCE. Default to false to keep backward compatibility.

e.g. true | false


We recommend all new projects which make use of to use @GeneratedValue to also set hibernate.id.new_generator_mappings=true as the new generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing databases (if a sequence or a table is used for id generation).

Table 3.4. Hibernate JDBC and Connection Properties

Property namePurpose
hibernate.jdbc.fetch_sizeA non-zero value determines the JDBC fetch size (calls Statement.setFetchSize()).
hibernate.jdbc.batch_sizeA non-zero value enables use of JDBC2 batch updates by Hibernate.

e.g. recommended values between 5 and 30

hibernate.jdbc.batch_versioned_dataSet this property to true if your JDBC driver returns correct row counts from executeBatch(). It is usually safe to turn this option on. Hibernate will then use batched DML for automatically versioned data. Defaults to false.

e.g. true | false

hibernate.jdbc.factory_classSelect a custom org.hibernate.jdbc.Batcher. Most applications will not need this configuration property.

e.g. classname.of.BatcherFactory

hibernate.jdbc.use_scrollable_resultsetEnables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise.

e.g. true | false

hibernate.jdbc.use_streams_for_binaryUse streams when writing/reading binary or serializable types to/from JDBC. *system-level property*

e.g. true | false

hibernate.jdbc.use_get_generated_keysEnables use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, it tries to determine the driver capabilities using connection metadata.

e.g. true|false

hibernate.connection.provider_classThe classname of a custom org.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.

e.g. classname.of.ConnectionProvider

hibernate.connection.isolationSets the JDBC transaction isolation level. Check java.sql.Connection for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations.

e.g. 1, 2, 4, 8

hibernate.connection.autocommitEnables autocommit for JDBC pooled connections (it is not recommended).

e.g. true | false

hibernate.connection.release_modeSpecifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy.

e.g. auto (default) | on_close | after_transaction | after_statement

This setting only affects Sessions returned from SessionFactory.openSession. For Sessions obtained through SessionFactory.getCurrentSession, the CurrentSessionContext implementation configured for use controls the connection release mode for those Sessions. See Section 2.2, “Contextual sessions”

hibernate.connection.<propertyName>Pass the JDBC property <propertyName> to DriverManager.getConnection().
hibernate.jndi.<propertyName>Pass the property <propertyName> to the JNDI InitialContextFactory.

Table 3.5. Hibernate Cache Properties

Property namePurpose
hibernate.cache.provider_classThe classname of a custom CacheProvider.

e.g. classname.of.CacheProvider

hibernate.cache.use_minimal_putsOptimizes second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate, is enabled by default for clustered cache implementations.

e.g. true|false

hibernate.cache.use_query_cacheEnables the query cache. Individual queries still have to be set cachable.

e.g. true|false

hibernate.cache.use_second_level_cacheCan be used to completely disable the second level cache, which is enabled by default for classes which specify a <cache> mapping.

e.g. true|false

hibernate.cache.query_cache_factoryThe classname of a custom QueryCache interface, defaults to the built-in StandardQueryCache.

e.g. classname.of.QueryCache

hibernate.cache.region_prefixA prefix to use for second-level cache region names.

e.g. prefix

hibernate.cache.use_structured_entriesForces Hibernate to store data in the second-level cache in a more human-friendly format.

e.g. true|false

hibernate.cache.auto_evict_collection_cacheEnables the automatic eviction of a bi-directional association's collection cache when an element in the ManyToOne collection is added/updated/removed without properly managing the change on the OneToMany side.

e.g. true|false (default: false)

hibernate.cache.default_cache_concurrency_strategySetting used to give the name of the default org.hibernate.annotations.CacheConcurrencyStrategy to use when either @Cacheable or @Cache is used. @Cache(strategy="..") is used to override this default.

Table 3.7. Miscellaneous Properties

Property namePurpose
hibernate.current_session_context_classSupply a custom strategy for the scoping of the "current" Session. See Section 2.2, “Contextual sessions” for more information about the built-in strategies.

e.g. jta | thread | managed | custom.Class

hibernate.query.factory_classChooses the HQL parser implementation.

e.g. org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory or org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

hibernate.query.substitutionsIs used to map from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example).

e.g. hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

hibernate.hbm2ddl.autoAutomatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop


Comma-separated names of the optional files containing SQL DML statements executed during the SessionFactory creation. This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.

File order matters, the statements of a give file are executed before the statements of the following files. These statements are only executed if the schema is created ie if hibernate.hbm2ddl.auto is set to create or create-drop.

e.g. /humans.sql,/dogs.sql


The classname of a custom ImportSqlCommandExtractor (defaults to the built-in SingleLineSqlCommandExtractor). This is useful for implementing dedicated parser that extracts single SQL statements from each import file. Hibernate provides also MultipleLinesSqlCommandExtractor which supports instructions/comments and quoted strings spread over multiple lines (mandatory semicolon at the end of each statement).

e.g. classname.of.ImportSqlCommandExtractor


Enables the use of bytecode manipulation instead of runtime reflection. This is a System-level property and cannot be set in hibernate.cfg.xml. Reflection can sometimes be useful when troubleshooting. Hibernate always requires javassist even if you turn off the optimizer.

e.g. true | false


At the moment, javassist is the only supported bytecode provider.

e.g. javassist


Chooses the org.hibernate.cfg.NamingStrategy implementation when using Hibernate Entity Manager. org.hibernate.cfg.NamingStrategy is deprecated and this property is provided for backward-compatibity. See Section 3.6, “Implementing a Naming Strategy”

This property should not be used at the same time as hibernate.ejb.naming_strategy_delegator


Chooses the org.hibernate.cfg.naming.NamingStrategyDelegator implementation when using Hibernate Entity Manager. See Section 3.6, “Implementing a Naming Strategy”

Hibernate provides 2 implementations


org.hibernate.cfg.naming.LegacyNamingStrategyDelegator: This is the default value. This class is deprecated and is provided for backward compatibility.

org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator: This is the preferred value and generates default table and column names that comply with the JPA specification.

A different class that implements org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator may be specified.

This property should not be used at the same time as hibernate.ejb.naming_strategy_delegator.

Always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above. This means that you will not have to specify them manually.

Table 3.8. Hibernate SQL Dialects (hibernate.dialect)

CUBRID 8.3 and later org.hibernate.dialect.CUBRIDDialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
Firebird org.hibernate.dialect.FirebirdDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
H2 org.hibernate.dialect.H2Dialect
HyperSQL (HSQL) org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Ingres org.hibernate.dialect.IngresDialect
Ingres 9 org.hibernate.dialect.Ingres9Dialect
Ingres 10 org.hibernate.dialect.Ingres10Dialect
Interbase org.hibernate.dialect.InterbaseDialect
InterSystems Cache 2007.1 org.hibernate.dialect.Cache71Dialect
JDataStore org.hibernate.dialect.JDataStoreDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
Microsoft SQL Server 2012 org.hibernate.dialect.SQLServer2012Dialect
Mimer SQL org.hibernate.dialect.MimerSQLDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
MySQL5 org.hibernate.dialect.MySQL5Dialect
MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect
Oracle 8i org.hibernate.dialect.Oracle8iDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
Oracle 10g and later org.hibernate.dialect.Oracle10gDialect
Oracle TimesTen org.hibernate.dialect.TimesTenDialect
Pointbase org.hibernate.dialect.PointbaseDialect
PostgreSQL 8.1 org.hibernate.dialect.PostgreSQL81Dialect
PostgreSQL 8.2 org.hibernate.dialect.PostgreSQL82Dialect
PostgreSQL 9 and later org.hibernate.dialect.PostgreSQL9Dialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
SAP HANA (column store) org.hibernate.dialect.HANAColumnStoreDialect
SAP HANA (row store) org.hibernate.dialect.HANARowStoreDialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase 11 org.hibernate.dialect.Sybase11Dialect
Sybase ASE 15.5 org.hibernate.dialect.SybaseASE15Dialect
Sybase ASE 15.7 org.hibernate.dialect.SybaseASE157Dialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Teradata org.hibernate.dialect.TeradataDialect
Unisys OS 2200 RDMS org.hibernate.dialect.RDMSOS2200Dialect


Completely out of date. Hibernate uses JBoss Logging starting in 4.0. This will get documented as we migrate this content to the Developer Guide.

Hibernate utilizes Simple Logging Facade for Java (SLF4J) in order to log various system events. SLF4J can direct your logging output to several logging frameworks (NOP, Simple, log4j version 1.2, JDK 1.4 logging, JCL or logback) depending on your chosen binding. In order to setup logging you will need slf4j-api.jar in your classpath together with the jar file for your preferred binding - slf4j-log4j12.jar in the case of Log4J. See the SLF4J documentation for more detail. To use Log4j you will also need to place a log4j.properties file in your classpath. An example properties file is distributed with Hibernate in the src/ directory.

It is recommended that you familiarize yourself with Hibernate's log messages. A lot of work has been put into making the Hibernate log as detailed as possible, without making it unreadable. It is an essential troubleshooting device. The most interesting log categories are the following:

When developing applications with Hibernate, you should almost always work with debug enabled for the category org.hibernate.SQL, or, alternatively, the property hibernate.show_sql enabled.

org.hibernate.cfg.NamingStrategy and org.hibernate.cfg.naming.NamingStrategyDelegator interfaces allow you to specify a "naming standard" for database objects and schema elements.

You can provide rules for automatically generating database identifiers from Java identifiers or for processing "logical" column and table names given in the mapping file into "physical" table and column names. This feature helps reduce the verbosity of the mapping document, eliminating repetitive noise (TBL_ prefixes, for example). The default strategy used by Hibernate is quite minimal.

When annotations or JPA XML descriptors are used to map an entity, the org.hibernate.cfg.NamingStrategy API may not be flexible enough to properly generate default collection table or join column names that comply with the JPA specification. This is because the API does not provide all the necessary information (e.g., an entity's class name, along with its mapped name and primary table name) to compute the names properly. Due to this limitation, org.hibernate.cfg.NamingStrategy has been deprecated.


org.hibernate.cfg.naming.NamingStrategyDelegator is a temporary replacement for org.hibernate.cfg.NamingStrategy that addresses limitations and provides more flexibility in a more-or-less compatible way. A more comprehensive solution will be introduced in Hibernate 5.0 that will replace both org.hibernate.cfg.NamingStrategy and org.hibernate.cfg.naming.NamingStrategyDelegator.

For backward compatibility, the default org.hibernate.cfg.naming.NamingStrategyDelegator simply delegates table and column name generation to the default org.hibernate.cfg.NamingStrategy. This default org.hibernate.cfg.naming.NamingStrategyDelegator has also been deprecated and should be considered "legacy" code because it has the same limitations as org.hibernate.cfg.NamingStrategy.

Hibernate provides org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator as an alternative that generates default table and column names that comply with the JPA specification when annotations or JPA XML descriptors are used to map an entity. Table and column names generated for entities mapped using Hibernate Core hbm.xml are unaffected. This implementation must be explicitly configured in order to override the the default.


Hibernate allows an implementation of either org.hibernate.cfg.naming.NamingStrategyDelegator or org.hibernate.cfg.NamingStrategy to be configured. Both should not be configured at the same time.

To configure Hibernate Core to use org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator, call Configuration.setNamingStrategyDelegator() before adding mappings:

SessionFactory sf = new Configuration()

You can configure a custom implementation of org.hibernate.cfg.naming.NamingStrategyDelegator by replacing ImprovedNamingStrategyDelegator.DEFAULT_INSTANCE with the implementation class name.

To configure Hibernate Entity Manager to use org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator or a custom implementation, set the Hibernate configuration property hibernate.ejb.naming_strategy_delegator to the implementation class name


When using the default (legacy) implementation of org.hibernate.cfg.naming.NamingStrategyDelegator, Hibernate allows you to delegate to a different org.hibernate.cfg.NamingStrategy.

To configure Hibernate Core to delegate to a different org.hibernate.cfg.NamingStrategy, call Configuration.setNamingStrategy() before adding mappings:

SessionFactory sf = new Configuration()

org.hibernate.cfg.ImprovedNamingStrategy is a built-in strategy that might be a useful starting point for some applications.

To configure Hibernate Entity Manager to delegate to a different org.hibernate.cfg.NamingStrategy, set the Hibernate configuration property hibernate.ejb.naming_strategy to the implementation class name.

You can configure the persister implementation used to persist your entities and collections:

  • by default, Hibernate uses persisters that make sense in a relational model and follow Java Persistence's specification

  • you can define a PersisterClassProvider implementation that provides the persister class used of a given entity or collection

  • finally, you can override them on a per entity and collection basis in the mapping using @Persister or its XML equivalent

The latter in the list the higher in priority.

You can pass the PersisterClassProvider instance to the Configuration object.

SessionFactory sf = new Configuration()

The persister class provider methods, when returning a non null persister class, override the default Hibernate persisters. The entity name or the collection role are passed to the methods. It is a nice way to centralize the overriding logic of the persisters instead of spreading them on each entity or collection mapping.

An alternative approach to configuration is to specify a full configuration in a file named hibernate.cfg.xml. This file can be used as a replacement for the hibernate.properties file or, if both are present, to override properties.

The XML configuration file is by default expected to be in the root of your CLASSPATH. Here is an example:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"


    <!-- a SessionFactory instance listed as /jndi/name -->

        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="org/hibernate/auction/Item.hbm.xml"/>
        <mapping resource="org/hibernate/auction/Bid.hbm.xml"/>

        <!-- cache settings -->
        <class-cache class="org.hibernate.auction.Item" usage="read-write"/>
        <class-cache class="org.hibernate.auction.Bid" usage="read-only"/>
        <collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>



The advantage of this approach is the externalization of the mapping file names to configuration. The hibernate.cfg.xml is also more convenient once you have to tune the Hibernate cache. It is your choice to use either hibernate.properties or hibernate.cfg.xml. Both are equivalent, except for the above mentioned benefits of using the XML syntax.

With the XML configuration, starting Hibernate is then as simple as:

SessionFactory sf = new Configuration().configure().buildSessionFactory();

You can select a different XML configuration file using:

SessionFactory sf = new Configuration()

Hibernate has the following integration points for J2EE infrastructure:

  • Container-managed datasources: Hibernate can use JDBC connections managed by the container and provided through JNDI. Usually, a JTA compatible TransactionManager and a ResourceManager take care of transaction management (CMT), especially distributed transaction handling across several datasources. You can also demarcate transaction boundaries programmatically (BMT), or you might want to use the optional Hibernate Transaction API for this to keep your code portable.

  • Automatic JNDI binding: Hibernate can bind its SessionFactory to JNDI after startup.

  • JTA Session binding: the Hibernate Session can be automatically bound to the scope of JTA transactions. Simply lookup the SessionFactory from JNDI and get the current Session. Let Hibernate manage flushing and closing the Session when your JTA transaction completes. Transaction demarcation is either declarative (CMT) or programmatic (BMT/UserTransaction).

  • JMX deployment: if you have a JMX capable application server (e.g. JBoss AS), you can choose to deploy Hibernate as a managed MBean. This saves you the one line startup code to build your SessionFactory from a Configuration. The container will startup your HibernateService and also take care of service dependencies (datasource has to be available before Hibernate starts, etc).

Depending on your environment, you might have to set the configuration option hibernate.connection.aggressive_release to true if your application server shows "connection containment" exceptions.

The Hibernate Session API is independent of any transaction demarcation system in your architecture. If you let Hibernate use JDBC directly through a connection pool, you can begin and end your transactions by calling the JDBC API. If you run in a J2EE application server, you might want to use bean-managed transactions and call the JTA API and UserTransaction when needed.

To keep your code portable between these two (and other) environments we recommend the optional Hibernate Transaction API, which wraps and hides the underlying system. You have to specify a factory class for Transaction instances by setting the Hibernate configuration property hibernate.transaction.factory_class.

There are three standard, or built-in, choices:


delegates to database (JDBC) transactions (default)


delegates to container-managed transactions if an existing transaction is underway in this context (for example, EJB session bean method). Otherwise, a new transaction is started and bean-managed transactions are used.


delegates to container-managed JTA transactions

You can also define your own transaction strategies (for a CORBA transaction service, for example).

Some features in Hibernate (i.e., the second level cache, Contextual Sessions with JTA, etc.) require access to the JTA TransactionManager in a managed environment. In an application server, since J2EE does not standardize a single mechanism, you have to specify how Hibernate should obtain a reference to the TransactionManager:

A JNDI-bound Hibernate SessionFactory can simplify the lookup function of the factory and create new Sessions. This is not, however, related to a JNDI bound Datasource; both simply use the same registry.

If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (e.g. java:hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. This is especially useful in environments with a read-only JNDI default implementation (in Tomcat, for example).

When binding the SessionFactory to JNDI, Hibernate will use the values of hibernate.jndi.url, hibernate.jndi.class to instantiate an initial context. If they are not specified, the default InitialContext will be used.

Hibernate will automatically place the SessionFactory in JNDI after you call cfg.buildSessionFactory(). This means you will have this call in some startup code, or utility class in your application, unless you use JMX deployment with the HibernateService (this is discussed later in greater detail).

If you use a JNDI SessionFactory, an EJB or any other class, you can obtain the SessionFactory using a JNDI lookup.

It is recommended that you bind the SessionFactory to JNDI in a managed environment and use a static singleton otherwise. To shield your application code from these details, we also recommend to hide the actual lookup code for a SessionFactory in a helper class, such as HibernateUtil.getSessionFactory(). Note that such a class is also a convenient way to startup Hibernate—see chapter 1.

The easiest way to handle Sessions and transactions is Hibernate's automatic "current" Session management. For a discussion of contextual sessions see Section 2.2, “Contextual sessions”. Using the "jta" session context, if there is no Hibernate Session associated with the current JTA transaction, one will be started and associated with that JTA transaction the first time you call sessionFactory.getCurrentSession(). The Sessions retrieved via getCurrentSession() in the "jta" context are set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement. This allows the Sessions to be managed by the life cycle of the JTA transaction to which it is associated, keeping user code clean of such management concerns. Your code can either use JTA programmatically through UserTransaction, or (recommended for portable code) use the Hibernate Transaction API to set transaction boundaries. If you run in an EJB container, declarative transaction demarcation with CMT is preferred.