Hibernate.org Community Documentation

- Prev
- Next

## Chapter 1. Database access

## 1.1. Connecting

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

## Note

The built-in connection pool is not intended for production environments.

Hibernate obtains JDBC connections as needed though the `org.hibernate.service.jdbc.connections.spi.ConnectionProvider` interface which is a service contract. Applications may also supply their own `org.hibernate.service.jdbc.connections.spi.ConnectionProvider` implementation to define a custom approach for supplying connections to Hibernate (from a different connection pool implementation, for example).

### 1.1.1. Configuration

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.PostgreSQLDialect

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>

#### 1.1.1.1. Programatic 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 -D`property`=`value`

### 1.1.2. Obtaining a JDBC connection

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.

Example 1.6. Specifying configuration properties

    Session session = sessions.openSession();

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.

## 1.2. Connection pooling

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.

### 1.2.1. c3p0 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

### 1.2.2. Proxool connection pool

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.

### 1.2.3. Obtaining connections from an application server, using JNDI

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.

### 1.2.4. Other connection-specific configuration

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 `org.hibernate.service.jdbc.connections.spi.ConnectionProvider` and specifying your custom implementation with the hibernate.connection.provider_class property.

### 1.2.5. Optional configuration properties

In addition to the properties mentioned in the previous sections, Hibernate includes many other optional properties. See ??? for a more complete list.

## 1.3. Dialects

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
--- | ---
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
HypersonicSQL | org.hibernate.dialect.HSQLDialect
Informix | org.hibernate.dialect.InformixDialect
Interbase | org.hibernate.dialect.InterbaseDialect
Ingres | org.hibernate.dialect.IngresDialect
Microsoft SQL Server 2005 | org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 | org.hibernate.dialect.SQLServer2008Dialect
Mckoi SQL | org.hibernate.dialect.MckoiDialect
MySQL | org.hibernate.dialect.MySQLDialect
MySQL with InnoDB | org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM | org.hibernate.dialect.MySQLMyISAMDialect
Oracle 8i | org.hibernate.dialect.Oracle8iDialect
Oracle 9i | org.hibernate.dialect.Oracle9iDialect
Oracle 10g | org.hibernate.dialect.Oracle10gDialect
Pointbase | org.hibernate.dialect.PointbaseDialect
PostgreSQL | org.hibernate.dialect.PostgreSQLDialect
Progress | org.hibernate.dialect.ProgressDialect
SAP DB | org.hibernate.dialect.SAPDBDialect
Sybase ASE 15.5 | org.hibernate.dialect.SybaseASE15Dialect
Sybase ASE 15.7 | org.hibernate.dialect.SybaseASE157Dialect
Sybase Anywhere | org.hibernate.dialect.SybaseAnywhereDialect

### 1.3.1. Specifying the Dialect to use

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.

### 1.3.2. Dialect resolution

Assuming a `org.hibernate.service.jdbc.connections.spi.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 `org.hibernate.service.jdbc.connections.spi.ConnectionProvider`.

This functionality is provided by a series of `org.hibernate.service.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.service.jdbc.dialect.spi.DialectResolver` as follows:

Registered `org.hibernate.service.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.

## 1.4. Automatic schema generation with SchemaExport

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.

## Note

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.

### 1.4.1. Customizing the 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 | `true` or `false` | Whether a column is allowed to hold null values
unique | `true` or `false` | 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

1. 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"/>

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. Currently, the specified value of the unique-key attribute does not name the constraint in the generated DDL. It only groups the columns in the mapping file.

       <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"/>

3. 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"/>

4. 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>

5. 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"/>

       </property>

6. 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>

7. 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>

8. 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>

### 1.4.2. Running the SchemaExport tool

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.SchemaExport options 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=`my_schema.ddl` | output the ddl script to a file
--naming=`eg.MyNamingStrategy` | select a NamingStrategy
--config=`hibernate.cfg.xml` | read Hibernate configuration from an XML file
--properties=`hibernate.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

Example 1.8. Embedding SchemaExport into your application

    Configuration cfg = ....;

    new SchemaExport(cfg).create(false, true);

- PrevPreface
- Up
- Home
- NextChapter 2. Transactions and concurrency control