Hibernate.orgCommunity Documentation

Chapter 1. Database access

Table of Contents

1.1. Connecting
1.1.1. Configuration
1.1.2. Obtaining a JDBC connection
1.2. Connection pooling
1.2.1. c3p0 connection pool
1.2.2. Proxool connection pool
1.2.3. Obtaining connections from an application server, using JNDI
1.2.4. Other connection-specific configuration
1.2.5. Optional configuration properties
1.3. Dialects
1.3.1. Specifying the Dialect to use
1.3.2. Dialect resolution
1.4. Automatic schema generation with SchemaExport
1.4.1. Customizing the mapping files
1.4.2. Running the SchemaExport tool

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




Other ways to configure Hibernate programmatically

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

  • Set System properties using java -Dproperty=value

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.

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

DatabaseDialect
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

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.

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


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