Hibernate.orgCommunity Documentation
Table of Contents
Hibernate connects to databases on behalf of your application. It can connect through a variety of mechanisms, including:
Stand-alone built-in connection pool
javax.sql.DataSource
Connection pools, including support for two different third-party opensource JDBC connection pools:
c3p0
proxool
Application-supplied JDBC connections. This is not a recommended approach and exists for legacy reasons
The built-in connection pool is not intended for production environments.
Hibernate obtains JDBC connections as needed though the
ConnectionProvider
interface
which is a service contract. Applications may also supply their own
ConnectionProvider
implementation
to define a custom approach for supplying connections to Hibernate (from a different connection pool
implementation, for example).
You can configure database connections using a properties file, an XML deployment descriptor or programmatically.
Example 1.1. hibernate.properties
for a c3p0 connection pool
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.PostgreSQL82Dialect
Example 1.2. hibernate.cfg.xml
for a connection to the bundled HSQL database
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
</session-factory>
</hibernate-configuration>
An instance of object 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
builds an immutable
org.hibernate.SessionFactory
, and compiles the mappings from various XML mapping
files. You can specify the mapping files directly, or Hibernate can find them for you.
Example 1.3. Specifying the mapping files directly
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 method
addResource()
.
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
Example 1.4. Letting Hibernate find the mapping files for you
The addClass()
method directs Hibernate to search the CLASSPATH for the mapping
files, eliminating hard-coded file names. In the following example, it searches for
org/hibernate/auction/Item.hbm.xml
and
org/hibernate/auction/Bid.hbm.xml
.
Configuration cfg = new Configuration()
.addClass(org.hibernate.auction.Item.class)
.addClass(org.hibernate.auction.Bid.class);
Example 1.5. Specifying configuration properties
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");
Other ways to configure Hibernate programmatically
Pass an instance of java.util.Properties
to
Configuration.setProperties()
.
Set System properties using java
-Dproperty
=value
After you configure the Most important Hibernate JDBC properties, you can use method
openSession
of class org.hibernate.SessionFactory
to open
sessions. Sessions will obtain JDBC connections as needed based on the provided configuration.
Most important Hibernate JDBC properties
hibernate.connection.driver_class
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
hibernate.connection.pool_size
All available Hibernate settings are defined as constants and discussed on the
org.hibernate.cfg.AvailableSettings
interface. See its source code or
JavaDoc for details.
Hibernate's internal connection pooling algorithm is rudimentary, and is provided for development and testing purposes. Use a third-party pool for best performance and stability. To use a third-party pool, replace the hibernate.connection.pool_size property with settings specific to your connection pool of choice. This disables Hibernate's internal connection pool.
C3P0 is an open source JDBC connection pool distributed along with Hibernate in the lib/
directory. Hibernate uses its org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider
for
connection pooling if you set the hibernate.c3p0.* properties. properties.
Important configuration properties for the c3p0 connection pool
hibernate.c3p0.min_size
hibernate.c3p0.max_size
hibernate.c3p0.timeout
hibernate.c3p0.max_statements
Proxool is another open source JDBC connection pool distributed along with Hibernate in the
lib/
directory. Hibernate uses its
org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider
for connection pooling if you set the
hibernate.proxool.* properties. Unlike c3p0, proxool requires some additional configuration
parameters, as described by the Proxool documentation available at http://proxool.sourceforge.net/configure.html.
Table 1.1. Important configuration properties for the Proxool connection pool
Property | Description |
---|---|
hibernate.proxool.xml | Configure Proxool provider using an XML file (.xml is appended automatically) |
hibernate.proxool.properties | Configure the Proxool provider using a properties file (.properties is appended automatically) |
hibernate.proxool.existing_pool | Whether to configure the Proxool provider from an existing pool |
hibernate.proxool.pool_alias | Proxool pool alias to use. Required. |
To use Hibernate inside an application server, configure Hibernate to obtain connections from an application
server javax.sql.Datasource
registered in JNDI, by setting at least one of the following
properties:
Important Hibernate properties for JNDI datasources
hibernate.connection.datasource (required)
hibernate.jndi.url
hibernate.jndi.class
hibernate.connection.username
hibernate.connection.password
JDBC connections obtained from a JNDI datasource automatically participate in the container-managed transactions of the application server.
You can pass arbitrary connection properties by prepending hibernate.connection
to the
connection property name. For example, specify a charSet connection property as
hibernate.connection.charSet.
You can define your own plugin strategy for obtaining JDBC connections by implementing the interface
ConnectionProvider
and specifying your custom
implementation with the hibernate.connection.provider_class property.
In addition to the properties mentioned in the previous sections, Hibernate includes many other optional properties. See ??? for a more complete list.
Although SQL is relatively standardized, each database vendor uses a subset of supported syntax. This is referred
to as a dialect. Hibernate handles variations across these dialects through its
org.hibernate.dialect.Dialect
class and the various subclasses for each vendor dialect.
Table 1.2. Supported database dialects
Database | 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
|
The developer may manually specify the Dialect to use by setting the
hibernate.dialect configuration property to the name of a specific
org.hibernate.dialect.Dialect
class to use.
Assuming a ConnectionProvider
has been
set up, Hibernate will attempt to automatically determine the Dialect to use based on the
java.sql.DatabaseMetaData
reported by a
java.sql.Connection
obtained from that
ConnectionProvider
.
This functionality is provided by a series of
org.hibernate.engine.jdbc.dialect.spi.DialectResolver
instances registered
with Hibernate internally. Hibernate comes with a standard set of recognitions. If your application
requires extra Dialect resolution capabilities, it would simply register a custom implementation
of org.hibernate.engine.jdbc.dialect.spi.DialectResolver
as follows:
Registered org.hibernate.engine.jdbc.dialect.spi.DialectResolver
are
prepended to an internal list of resolvers, so they take precedence
before any already registered resolvers including the standard one.
SchemaExport is a Hibernate utility which generates DDL from your mapping files. The generated schema includes referential integrity constraints, primary and foreign keys, for entity and collection tables. It also creates tables and sequences for mapped identifier generators.
You must specify a SQL Dialect via the hibernate.dialect property when using this tool, because DDL is highly vendor-specific. See Section 1.3, “Dialects” for information.
Before Hibernate can generate your schema, you must customize your mapping files.
Hibernate provides several elements and attributes to customize your mapping files. They are listed in Table 1.3, “Elements and attributes provided for customizing mapping files”, and a logical order of customization is presented in Procedure 1.1, “Customizing the schema”.
Table 1.3. Elements and attributes provided for customizing mapping files
Name | Type of value | Description |
---|---|---|
length | number | Column length |
precision | number | Decimal precision of column |
scale | number | Decimal scale of column |
not-null |
| Whether a column is allowed to hold null values |
unique |
| Whether values in the column must be unique |
index | string | The name of a multi-column index |
unique-key | string | The name of a multi-column unique constraint |
foreign-key | string | The name of the foreign key constraint generated for an association. This applies to
<one-to-one>, <many-to-one>, <key>, and <many-to-many> mapping
elements. inverse="true" sides are skipped by SchemaExport. |
sql-type | string | Overrides the default column type. This applies to the <column> element only. |
default | string | Default value for the column |
check | string | An SQL check constraint on either a column or atable |
Procedure 1.1. Customizing the schema
Set the length, precision, and scale of mapping elements.
Many Hibernate mapping elements define optional attributes named length
,
precision
, and scale
.
<property name="zip" length="5"/>
<property name="balance" precision="12" scale="2"/>
Set the not-null
, UNIQUE
, unique-key
attributes.
The not-null
and UNIQUE
attributes generate constraints on table columns.
The unique-key attribute groups columns in a single, unique key constraint. The attribute overrides the name of any generated unique key constraint.
<many-to-one name="bar" column="barId" not-null="true"/>
<element column="serialNumber" type="long" not-null="true" unique="true"/>
<many-to-one name="org" column="orgId" unique-key="OrgEmployeeId"/>
<property name="employeeId" unique-key="OrgEmployee"/>
Set the index
and foreign-key
attributes.
The index
attribute specifies the name of an index for Hibernate to create using the mapped
column or columns. You can group multiple columns into the same index by assigning them the same index name.
A foreign-key attribute overrides the name of any generated foreign key constraint.
<many-to-one name="bar" column="barId" foreign-key="FKFooBar"/>
Set child <column>
elements.
Many mapping elements accept one or more child <column> elements. This is particularly useful for mapping types involving multiple columns.
<property name="name" type="my.customtypes.Name"/>
<column name="last" not-null="true" index="bar_idx" length="30"/>
<column name="first" not-null="true" index="bar_idx" length="20"/>
<column name="initial"/>
</property>
Set the default
attribute.
The default
attribute represents a default value for a column. Assign the same value to the
mapped property before saving a new instance of the mapped class.
<property name="credits" type="integer" insert="false">
<column name="credits" default="10"/>
</property>
<version name="version" type="integer" insert="false">
<column name="version" default="0"/>
</version>
Set the sql-type
attribure.
Use the sql-type
attribute to override the default mapping of a Hibernate type to SQL
datatype.
<property name="balance" type="float">
<column name="balance" sql-type="decimal(13,3)"/>
</property>
Set the check
attribute.
use the check
attribute to specify a check constraint.
<property name="foo" type="integer">
<column name="foo" check="foo > 10"/>
</property>
<class name="Foo" table="foos" check="bar < 100.0">
...
<property name="bar" type="float"/>
</class>
Add <comment> elements to your schema.
Use the <comment> element to specify comments for the generated schema.
<class name="Customer" table="CurCust">
<comment>Current customers only</comment>
...
</class>
The SchemaExport tool writes a DDL script to standard output, executes the DDL statements, or both.
Example 1.7. SchemaExport syntax
java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExportoptions
mapping_files
Table 1.4. SchemaExport Options
Option | Description |
---|---|
--quiet | do not output the script to standard output |
--drop | only drop the tables |
--create | only create the tables |
--text | do not export to the database |
--output= | output the ddl script to a file |
--naming= | select a NamingStrategy |
--namingdelegator= | select a NamingStrategyDelegator |
--config= | read Hibernate configuration from an XML file |
--properties= | read database properties from a file |
--format | format the generated SQL nicely in the script |
--delimiter= | set an end-of-line delimiter for the script |
The options, --naming
and --namingdelegator
, should not be used together.
Example 1.8. Embedding SchemaExport into your application
Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);