Hibernate.orgCommunity Documentation
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.
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
A org.hibernate.cfg.Configuration
also allows
you to specify configuration properties. For example:
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
.setProperty("hibernate.order_updates", "true");
If you want to get started
quicklyhibernate.properties
is the easiest
approach.
Session session = sessions.openSession(); // open a new Session
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.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
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:
Table 3.2. Hibernate Datasource Properties
Property name | Purpose |
---|---|
hibernate.connection.datasource | datasource JNDI name |
hibernate.jndi.url | URL of the JNDI provider (optional) |
hibernate.jndi.class | class of the JNDI
InitialContextFactory
(optional) |
hibernate.connection.username | database user (optional) |
hibernate.connection.password | database user password (optional) |
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 = \ org.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = \ org.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
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.
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 name | Purpose |
---|---|
hibernate.jdbc.fetch_size | A non-zero value determines the JDBC fetch size (calls
Statement.setFetchSize() ). |
hibernate.jdbc.batch_size | A non-zero value enables use of JDBC2 batch updates by
Hibernate. e.g.
recommended values between |
hibernate.jdbc.batch_versioned_data | Set 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. |
hibernate.jdbc.factory_class | Select a custom
org.hibernate.jdbc.Batcher . Most
applications will not need this configuration property.
e.g.
|
hibernate.jdbc.use_scrollable_resultset | Enables 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. |
hibernate.jdbc.use_streams_for_binary | Use streams when writing/reading binary
or serializable types to/from JDBC.
*system-level property* e.g. |
hibernate.jdbc.use_get_generated_keys | Enables 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.
|
hibernate.connection.provider_class | The classname of a custom
org.hibernate.connection.ConnectionProvider
which provides JDBC connections to Hibernate. e.g.
|
hibernate.connection.isolation | Sets 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. |
hibernate.connection.autocommit | Enables autocommit for JDBC pooled connections (it is not
recommended). e.g.
|
hibernate.connection.release_mode | Specifies 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. This setting
only affects |
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 name | Purpose |
---|---|
hibernate.cache.provider_class | The classname of a custom CacheProvider .
e.g.
|
hibernate.cache.use_minimal_puts | Optimizes second-level cache operation to minimize writes,
at the cost of more frequent reads. This setting is most useful
for clustered caches and, in Hibernate3, is enabled by default for
clustered cache implementations. e.g. |
hibernate.cache.use_query_cache | Enables the query cache. Individual queries still have to
be set cachable. e.g.
|
hibernate.cache.use_second_level_cache | Can be used to completely disable the second level cache,
which is enabled by default for classes which specify a
<cache> mapping. e.g. |
hibernate.cache.query_cache_factory | The classname of a custom QueryCache
interface, defaults to the built-in
StandardQueryCache . e.g.
|
hibernate.cache.region_prefix | A prefix to use for second-level cache region names.
e.g. |
hibernate.cache.use_structured_entries | Forces Hibernate to store data in the second-level cache in
a more human-friendly format. e.g. |
hibernate.cache.default_cache_concurrency_strategy | Setting 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.6. Hibernate Transaction Properties
Property name | Purpose |
---|---|
hibernate.transaction.factory_class | The classname of a TransactionFactory to
use with Hibernate Transaction API (defaults to
JDBCTransactionFactory ). e.g.
|
jta.UserTransaction | A JNDI name used by
JTATransactionFactory to obtain the JTA
UserTransaction from the application server.
e.g.
|
hibernate.transaction.manager_lookup_class | The classname of a
TransactionManagerLookup . It is required when
JVM-level caching is enabled or when using hilo generator in a JTA
environment. e.g.
|
hibernate.transaction.flush_before_completion | If enabled, the session will be automatically flushed
during the before completion phase of the transaction. Built-in
and automatic session context management is preferred, see Section 2.3, “Contextual sessions”. e.g. |
hibernate.transaction.auto_close_session | If enabled, the session will be automatically closed during
the after completion phase of the transaction. Built-in and
automatic session context management is preferred, see Section 2.3, “Contextual sessions”. e.g. |
Table 3.7. Miscellaneous Properties
Property name | Purpose |
---|---|
hibernate.current_session_context_class | Supply a custom strategy for the scoping of the "current"
Session . See Section 2.3, “Contextual sessions” for more information
about the built-in strategies. e.g. |
hibernate.query.factory_class | Chooses the HQL parser implementation. e.g.
|
hibernate.query.substitutions | Is used to map from tokens in Hibernate queries to SQL
tokens (tokens might be function or literal names, for example).
e.g.
|
hibernate.hbm2ddl.auto | Automatically 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.
|
hibernate.hbm2ddl.import_files | Comma-separated names of the optional files
containing SQL DML statements executed during the
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
e.g.
|
hibernate.bytecode.use_reflection_optimizer | Enables the use of bytecode manipulation instead of
runtime reflection. This is a System-level property and cannot be
set in e.g.
|
hibernate.bytecode.provider | Both javassist or cglib can be used as byte
manipulation engines; the default is
e.g. |
See Section 21.1, “Fetching strategies” for more information.
The properties prefixed by hibernate.cache
allow you to use a process or cluster scoped second-level cache system
with Hibernate. See the Section 21.2, “The Second Level Cache” for more
information.
You can define new Hibernate query tokens using
hibernate.query.substitutions
. For example:
hibernate.query.substitutions true=1, false=0
hibernate.query.substitutions toLowercase=LOWER
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.
You can configure the persister implementation used to persist your entities and collections:
The latter in the list the higher in priority.
You can pass the PersisterClassProvider
instance to the Configuration
object.
SessionFactory sf = new Configuration()
.setPersisterClassProvider(customPersisterClassProvider)
.addAnnotatedClass(Order.class)
.buildSessionFactory();
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory
name="java:hibernate/SessionFactory">
<!-- 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">
org.hibernate.transaction.JTATransactionFactory
</property>
<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"/>
</session-factory>
</hibernate-configuration>
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()
.configure("catdb.cfg.xml")
.buildSessionFactory();
Hibernate has the following integration points for J2EE infrastructure:
There are three standard, or built-in, choices:
You can also define your own transaction strategies (for a CORBA transaction service, for example).
The easiest way to handle Sessions
and
transactions is Hibernate's automatic "current"
Session
management. For a discussion of contextual
sessions see Section 2.3, “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
Session
s 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
Session
s 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.
Copyright © 2004 Red Hat, Inc.