Chapter 3. SessionFactory Configuration

Because Hibernate is designed to operate in many different environments, there are a large number of configuration parameters. Fortunately, most have sensible default values and Hibernate is distributed with an example hibernate.properties file that shows the various options.

3.1. Programmatic Configuration

An instance of net.sf.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to a relational database. These mappings are compiled from various XML mapping files. You may obtain a Configuration instance by instantiating it directly. Heres an example of setting up a datastore from mappings defined in two XML configuration files:

Configuration cfg = new Configuration()
    .addFile("Vertex.hbm.xml")
    .addFile("Edge.hbm.xml");

An alternative (better?) way is to let Hibernate load a mapping file using getResourceAsStream().

Configuration cfg = new Configuration()
    .addClass(eg.Vertex.class)
    .addClass(eg.Edge.class);

Then Hibernate will look for mapping files named /eg/Vertex.hbm.xml, /eg/Edge.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.

A Configuration also specifies various optional properties.

Properties props = new Properties();
...
Configuration cfg = new Configuration()
    .addClass(eg.Vertex.class)
    .addClass(eg.Edge.class)
    .setProperties(props);

A Configuration is intended as a configuration-time object, to be discarded once a SessionFactory is built.

3.2. Obtaining a SessionFactory

When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads. However, Hibernate does allow your application to instantiate more than one SessionFactory. This is useful if you are using more than one database.

SessionFactory sessions = cfg.buildSessionFactory();

3.3. User provided JDBC connection

A SessionFactory may open a Session on a user-provided JDBC connection. This design choice frees the application to obtain JDBC connections wherever it pleases. The application must be careful not to open two concurrent sessions on the same connection.

java.sql.Connection conn = datasource.getConnection();
Session sess = sessions.openSession(conn);

// start a new transaction
Transaction tx = sess.beginTransaction();

The last line here is optional - the application may choose to manage transactions by directly manipulating JTA or JDBC transactions. However, if you use a Hibernate Transaction (i.e., one of Hibernate's APIs), your client code will be abstracted away from the underlying implementation. (You could, for example, choose to switch to a CORBA transaction service at some future point, with no changes to application code.)

3.4. Hibernate provided JDBC connection

Alternatively, you can have the SessionFactory open connections for you. The SessionFactory must be provided with connection properties in one of the following ways:

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

  2. Place 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 (see below).

If you take this approach, opening a Session is as simple as:

Session sess = sessions.openSession(); // obtain a JDBC connection and
                                       // instantiate a new Session
// start a new transaction (optional)
Transaction tx = sess.beginTransaction();

All Hibernate property names and semantics are defined on the class net.sf.hibernate.cfg.Environment. We will now describe the most important settings.

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

Table 3.1. Hibernate JDBC Properties

Property namePurpose
hibernate.connection.driver_classjdbc driver class
hibernate.connection.urljdbc URL
hibernate.connection.usernamedatabase user
hibernate.connection.passworddatabase user password
hibernate.connection.pool_sizemaximum number of pooled connections

Hibernate's own connection pooling algorithm is 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.

C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib directory. Hibernate will use the built-in C3P0ConnectionProvider for connection pooling if you set the hibernate.c3p0.* properties. There is also built-in support for Apache DBCP and for Proxool. You must set the properties hibernate.dbcp.* (DBCP connection pool properties) and hibernate.dbcp.ps.* (DBCP statement cache properties) to enable DBCPConnectionProvider. Please refer the the Apache commons-pool documentation for the interpretation of these properties. You should set the hibernate.proxool.* properties if you wish to use Proxool.

For use inside an application server, Hibernate may obtain connections from a javax.sql.Datasource registered in JNDI. Set the following properties:

Table 3.2. Hibernate Datasource Properties

Propery namePurpose
hibernate.connection.datasourcedatasource JNDI name
hibernate.jndi.urlURL of the JNDI provider (optional)
hibernate.jndi.classclass of the JNDI InitialContextFactory (optional)
hibernate.connection.usernamedatabase user (optional)
hibernate.connection.passworddatabase user password (optional)

3.5. Other properties

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

System-level properties can only be set via java -Dproperty=value or be defined in hibernate.properties and not with an instance of Properties passed to the Configuration.

Table 3.3. Hibernate Configuration Properties

Property namePurpose
hibernate.dialectThe classname of a Hibernate Dialect - enables certain platform dependent features.

eg. full.classname.of.Dialect

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

eg. SCHEMA_NAME

hibernate.session_factory_nameBind this name to the SessionFactory.

eg. jndi/composite/name

hibernate.use_outer_joinEnables outer join fetching.

eg. true | false

hibernate.max_fetch_depthSet a maximum "depth" for the outer join fetch tree.

eg. recommended values between 0 and 3

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

eg. recommended values between 5 and 30

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

eg. true | false

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

eg. true | false

hibernate.cglib.use_reflection_optimizerEnables use of CGLIB instead of runtime reflection (System-level property, default is to use CGLIB where possible). Reflection can sometimes be useful when troubleshooting.

eg. true | false

hibernate.jndi.<propertyName>Pass the property propertyName to the JNDI InitialContextFactory (optional)
hibernate.connection.isolationSet the JDBC transaction isolation level (optional)

eg. 1, 2, 4, 8

hibernate.connection.<propertyName>Pass the JDBC property propertyName to DriverManager.getConnection().
hibernate.connection.provider_classThe classname of a custom ConnectionProvider

eg. classname.of.ConnectionProvider

hibernate.cache.provider_classThe classname of a custom CacheProvider

eg. classname.of.CacheProvider

hibernate.transaction.factory_classThe classname of a TransactionFactory to use with Hibernate Transaction API.

eg. classname.of.TransactionFactory

jta.UserTransactionA JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction.

eg. jndi/composite/name

hibernate.transaction.manager_lookup_classThe classname of a TransactionManagerLookup - required when JVM-level caching is enabled in a JTA environment.

eg. classname.of.TransactionManagerLookup

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

eg. hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

hibernate.show_sqlWrite all SQL statements to console (as an alternative to use of the logging functionality).

eg. true | false

hibernate.hbm2ddl.autoAutomatically export schema DDL.

eg. update | create | create-drop

3.5.1. SQL Dialects

You should always set the hibernate.dialect property to the correct net.sf.hibernate.dialect.Dialect subclass for your database. This is not strictly essential unless you wish to use native or sequence primary key generation or pessimistic locking (with, eg. Session.lock() or Query.setLockMode()). However, if you specify a dialect, Hibernate will use sensible defaults for some of the other properties listed above, saving you the effort of specifying them manually.

Table 3.4. Hibernate SQL Dialects (hibernate.dialect)

RDBMSDialect
DB2net.sf.hibernate.dialect.DB2Dialect
MySQLnet.sf.hibernate.dialect.MySQLDialect
SAP DBnet.sf.hibernate.dialect.SAPDBDialect
Oracle (any version)net.sf.hibernate.dialect.OracleDialect
Oracle 9net.sf.hibernate.dialect.Oracle9Dialect
Sybasenet.sf.hibernate.dialect.SybaseDialect
Sybase Anywherenet.sf.hibernate.dialect.SybaseAnywhereDialect
Progressnet.sf.hibernate.dialect.ProgressDialect
Mckoi SQLnet.sf.hibernate.dialect.MckoiDialect
Interbasenet.sf.hibernate.dialect.InterbaseDialect
Pointbasenet.sf.hibernate.dialect.PointbaseDialect
PostgreSQLnet.sf.hibernate.dialect.PostgreSQLDialect
HypersonicSQLnet.sf.hibernate.dialect.HSQLDialect
Microsoft SQL Servernet.sf.hibernate.dialect.SQLServerDialect
Ingresnet.sf.hibernate.dialect.IngresDialect
Informixnet.sf.hibernate.dialect.InformixDialect
FrontBasenet.sf.hibernate.dialect.FrontbaseDialect

3.5.2. Outer Join Fetching

If your database supports ANSI or Oracle style outer joins, outer join fetching might increase performance by limiting the number of round trips to and from the database (at the cost of possibly more work performed by the database itself). Outer join fetching allows a graph of objects connected by many-to-one, one-to-many or one-to-one associations to be retrieved in a single SQL SELECT.

By default, the fetched graph ends at leaf objects, collections, objects with proxies, or where circularities occur. For a particular association, fetching may be enabled or disabled (and the default behaviour overridden) by setting the outer-join attribute in the XML mapping. Outer join fetching may be disabled globally by setting the property hibernate.use_outer_join to false. You may limit the maximum depth of the fetched graph of objects using hibernate.max_fetch_depth.

3.5.3. Binary Streams

Oracle limits the size of byte arrays that may be passed to/from its JDBC driver. If you wish to use large instances of binary or serializable type, you should enable hibernate.jdbc.use_streams_for_binary. This is a JVM-level setting only.

3.5.4. SQL Logging to Console

hibernate.show_sql forces Hibernate to write SQL statements to the console. This is provided as an easy alternative to enabling logging.

3.5.5. Custom ConnectionProvider

You may define your own plugin strategy for obtaining JDBC connections by implementing the interface net.sf.hibernate.connection.ConnectionProvider. You may select a custom implementation by setting hibernate.connection.provider_class.

3.5.6. Common connection properties

Certain configuration properties affect all of the built-in connection providers apart from DatasourceConnectionProvider. These include: hibernate.connection.driver_class, hibernate.connection.url, hibernate.connection.username and hibernate.connection.password.

hibernate.connection.isolation should be specified as an integer value. (Check java.sql.Connection for meaningful values but note that most databases do not support all isolation levels.)

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

3.5.7. Custom CacheProvider

You may integrate a JVM-level (or clustered) cache by implementing the interface net.sf.hibernate.connection.ConnectionProvider. You may select the custom implementation by setting hibernate.cache.provider_class.

3.5.8. Transaction Strategy

If you wish to use the Hibernate Transaction API, you must specify a factory class for Transaction instances by setting the property hibernate.transaction.factory_class. There are two standard (built-in) choices:

net.sf.hibernate.transaction.JDBCTransactionFactory

delegates to database (JDBC) transactions

net.sf.hibernate.transaction.JTATransactionFactory

delegates to JTA (if an existing transaction is underway, the Session performs its work in that context, otherwise a new transaction is started)

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

If you wish to use JVM-level caching of mutable data in a JTA environment, you must specify a strategy for obtaining the JTA TransactionManager.

Table 3.5. JTA TransactionManagers

Transaction FactoryApplication Server
net.sf.hibernate.transaction.JBossTransactionManagerLookupJBoss
net.sf.hibernate.transaction.WeblogicTransactionManagerLookupWeblogic
net.sf.hibernate.transaction.WebSphereTransactionManagerLookupWebSphere
net.sf.hibernate.transaction.OrionTransactionManagerLookupOrion
net.sf.hibernate.transaction.ResinTransactionManagerLookupResin
net.sf.hibernate.transaction.JOTMTransactionManagerLookupJOTM
net.sf.hibernate.transaction.JOnASTransactionManagerLookupJOnAS
net.sf.hibernate.transaction.JRun4TransactionManagerLookupJRun4

3.5.9. JNDI-bound SessionFactory

If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (eg. java:comp/env/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, eg. Tomcat.)

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.

If you do choose to use JNDI, an EJB or other utility class may obtain the SessionFactory using a JNDI lookup.

3.5.10. Query Language Substitution

You may define new Hibernate query tokens using hibernate.query.substitutions. For example:

hibernate.query.substitutions true=1, false=0

would cause the tokens true and false to be translated to integer literals in the generated SQL.

hibernate.query.substitutions toLowercase=LOWER

would allow you to rename the SQL LOWER function.

3.6. XML Configuration File

An alternative approach is to specify a full configuration in a file named hibernate.cfg.xml. The configuration file is expected to be in the root of your CLASSPATH.

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

 "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory 
        name="java:comp/env/hibernate/SessionFactory">

        <!-- properties -->
        <property name="connection.datasource">my/first/datasource</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="use_outer_join">true</property>
        <property name="transaction.factory_class">net.sf.hibernate.transaction.JTATransactionFactory</property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="eg/Edge.hbm.xml"/>
        <mapping resource="eg/Vertex.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

Configuring Hibernate is then as simple as

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

You can pick a different configuration file using

SessionFactory sf = new Configuration()
    .configure("catdb.cfg.xml")
    .buildSessionFactory();

3.7. Logging

Hibernate logs various events using Apache commons-logging. The commons-logging service will direct output to either Apache log4j (if you include log4j.jar in your classpath) or JDK1.4 logging (if running under JDK1.4 or above). You may download log4j from http://jakarta.apache.org. To use log4j you will need to place a log4j.properties file in your classpath. An example properties file is distributed with Hibernate.

We strongly recommend 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.