
Hibernate Developer Documentation - Chapter I. Accessing the Database
- Tutorial
I present to you the translation of the first chapter of the official Hibernate documentation .
The translation of the article is relevant for Hibernate version 4.2.19. Final The next
chapter is the Hibernate Developer Documentation - Chapter II. Transactions and multithreading control
Contents
Foreword
1. Access to the database
1.1. Connection
1.1.1. Configuration
1.1.2. Getting JDBC Connection
1.2. Connection pooling
1.2.1. Pooling with c3p0
1.2.2. Pooling with Proxool
1.2.3. Getting connections from the application server, through JNDI
1.2.4. Other on the configuration of connections
1.2.5. Optional configuration properties
1.3. Dialects
1.3.1. Indication of the dialect for use
1.3.2. Dialect Resolution
1.4. Automatic circuit generation using Schema Export
1.4.1. Customizing the mapping files
1.4.2. Launching SchemaExport Tool
Working with both object-oriented software and relational databases (hereinafter referred to as DB, approx. Transl.) Can be very burdensome and costly in terms of time spent. Development costs are significantly higher due to the mismatch of the paradigms of data representation in objects and relational databases. Hibernate is a solution to the so-called Object Relational Projection for Java. The term object-relational projection refers to the technique of projecting (mapping) data from an object representation model to a relational representation model (and vice versa). See en.wikipedia.org/wiki/Object-relational_mapping for more details.
Hibernate not only cares about projecting Java classes into database tables (as well as projecting basic Java types to SQL types), but also provides mechanisms for generating queries and data samples. It can significantly reduce development time, which was done in the old style by manually working with data using SQL and JDBC. The main goal of Hibernate architectural design is to save the developer from the daily tasks of working with database data by eliminating the need to write your own logic for working with data through SQL and JDBC. However, unlike other persistence solutions, Hibernate does not hide your ability to use the full power of SQL, and ensures that your investment in relational technology and knowledge is still valid.
Hibernate may not be the best solution for applications that store all their business logic in stored procedures, it is more suitable for object-oriented models and logic in the middle (business) layer of an application written in Java. However, Hibernate can certainly help you get rid of or encapsulate the logic of a specific SQL code, as well as cope with the daily tasks of translating the results of your queries from a table view into an object graph.
Hibernate connects to the database on behalf of your application. The connection can be carried out through various mechanisms, namely:
Hibernate receives JDBC connections as needed through the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface . Applications can also provide their implementations of the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface to define a custom approach for providing connections to Hibernate. (From another connection pool, for example)
You can configure the connection to the database using the property file, via the XML deployment descriptor, or programmatically.
Example 1.1 hibernate.properties for c3p0 connection pool
Example 1.2 hibernate.cfg.xml to connect to the embedded HSQL database
An instance of the org.hibernate.cfg.Configuration object represents a complete set of database mapping types. Object org.hibernate.cfg.Configuration creates immutabelny object org.hibernate.SessionFactory , and compiles mapping of various XML-files. You can specify files for mapping directly, or Hibernate can find them for you.
Example 1.3 Specifying files for mapping directly
You can get the org.hibernate.cfg.Configuration object by creating it and specifying XML documents for mapping directly. If the mapping files are in the classpath, use the addResource () method.
Example 1.4 Hibernate finds files for you.
The addClass () method tells Hibernate to look for mapping files through the classpath based on the class name, while saving you the trouble of specifying the file names yourself. In the following example, he searches for org / hibernate / auction / Item.hbm.xml and org / hibernate / auction / Bid.hbm.xml .
Example 1.5 Specifying configuration properties
Other ways to programmatically configure Hibernate
After you configure the basic properties of the jdbc-the Hibernate , you can use the method openSession class org.hibernate.SessionFactory to open sessions. Sessions will open JDBC connections on demand based on the configuration provided.
Example 1.6 Opening session
Hibernate core jdbc properties
The internal connection pooling algorithm in Hibernate is fairly rudimentary, and is needed, for the most part, for development and testing. Use third-party (3 rd party) pools for better performance and stability. To use the 3 rd party pool, replace the value of the hibernate.connection.pool_size property with the specifics of your selected pool. This will disable the use of the built-in Hibernate pool.
C3P0 is the open source JDBC connection pool distributed with Hibernate in the lib / directory. Hibernate will use its own org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider to pool connections when setting the hibernate.c3p0 properties. *
Important configuration properties for c3p0
Proxool is another open source pool distributed with Hibernate in the lib / directory. Hibernate will use its own org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider to pool connections when configured with hibernate.proxool. *. Unlike c3p0, proxool requires some additional settings, which are described in the documentation available at proxool.sourceforge.net/configure.html .
Table 1.1. Important configuration properties for the Proxool connection pool
To use Hibernate inside an application server, configure Hibernate to receive connections from javax.sql.Datasource registered in JNDI by setting at least one of the following properties:
Important properties for JNDI data sources
JDBC connections received from a JNDI data source automatically participate in container-managed application server transactions.
You can pass arbitrary connection properties by adding hibernate.connection in front of them . For example, to specify the charSet property, use the name hibernate.connection.charSet .
You can define your strategy for receiving JDBC connections by implementing the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface and specifying your custom implementation using the hibernate.connection.provider_class property
In addition to the properties listed above, Hibernate includes many other parameters. See a more detailed list at http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html_single/ .
Although SQL is relatively standardized, each DBMS vendor uses its own subset of supported syntaxes. This has another term called a dialect. Hibernate supports various dialect variations through the org.hibernate.dialect.Dialect class and various subclasses for each vendor dialect.
Table 1.2. Supported DBMS dialects

The developer can manually specify the dialect to use by specifying the appropriate subclass name org.hibernate.dialect.Dialect in the hibernate.dialect property .
Assuming in advance that org.hibernate.service.jdbc.connections.spi.ConnectionProvider has been configured, Hibernate will try to automatically detect the dialect based on the java.sql.DatabaseMetaData obtained from the java.sql.Connection object , which in turn is obtained from org. hibernate.service.jdbc.connections.spi.ConnectionProvider .
This functionality is provided by instances of org.hibernate.service.jdbc.dialect.spi.DialectResolver registered with the framework itself. Hibernate comes with a standard recognition set. If your application requires additional dialect recognition capabilities, it is possible to register a custom implementationorg.hibernate.service.jdbc.dialect.spi.DialectResolver , as shown below
Registered implementations of org.hibernate.service.jdbc.dialect.spi.DialectResolver are added to the internal resolver list so that they take precedence over previously registered resolvers , as well as over the standard.
SchemaExport is a Hibernate utility that generates DDL scripts from your mapping files. The generated schema includes referential integrity constraints, primary and foreign keys for entities and collection tables. It also creates tables for sequences and projected identity generators.
Before Hibernate can generate your schema, you must customize your mapping files.
Hibernate provides a number of elements and attributes for your mapping files. They are listed in Table 1.3, “Elements and Attributes Provided for Customizing Mapping Files,” and the logical order of customization is presented in Procedure 1.1, “Customizing the Schema”.
Table 1.3. Elements and attributes provided for customizing mapping files
Procedure 1.1. Customization of the scheme
1. Setting the length, accuracy, and scale of the mapping elements.
Many mapping elements define optional attributes, such as length , precision , and scale .
2. Setting not-null, UNIQUE, unique-key attributes.
not-null and UNIQUE attributes generate table column constraints.
The unique-key attribute groups columns into a single uniqueness constraint. The attribute overrides the name of any generated uniqueness constraint.
3. Setting the index and foreign-key attributes.
The index attribute indicates the name of the index to create it using the projected column or columns. You can group several columns by one index, indicating in each of them the name of the same index.
The foreign key attribute overrides the name of any generated foreign key constraint.
4. Installation of subsidiaries-elements.
Many mapping elements allow the use of childelements. This is useful for mapping types that include multiple columns.
5. Setting the default attribute.
The default attribute is the default value for the column. Add a value to the projected property before saving a new instance of the class.
6. Установка атрибута sql-type.
Используйте атрибут sql-type для переопределения маппинга по-умолчанию для типов Java на типы SQL.
7. Установка атрибута check.
Используйте атрибут check для указания ограничения check.
8.Добавление элементов к вашей схеме.
Используйте элемент для указания комментариев для сгенерированной схемы.
Инструмент SchemaExport записывает DDL-скрипт в стандартный поток вывода, исполняет DDL, или и то, и другое сразу.
Пример 1.7. Синтаксис SchemaExport
Таблица 1.4. Опции SchemaExport
Example 1.8 Embedding SchemaExport in your application
The translation of the article is relevant for Hibernate version 4.2.19. Final The next
chapter is the Hibernate Developer Documentation - Chapter II. Transactions and multithreading control
Contents
Foreword
1. Access to the database
1.1. Connection
1.1.1. Configuration
1.1.2. Getting JDBC Connection
1.2. Connection pooling
1.2.1. Pooling with c3p0
1.2.2. Pooling with Proxool
1.2.3. Getting connections from the application server, through JNDI
1.2.4. Other on the configuration of connections
1.2.5. Optional configuration properties
1.3. Dialects
1.3.1. Indication of the dialect for use
1.3.2. Dialect Resolution
1.4. Automatic circuit generation using Schema Export
1.4.1. Customizing the mapping files
1.4.2. Launching SchemaExport Tool
Foreword
Working with both object-oriented software and relational databases (hereinafter referred to as DB, approx. Transl.) Can be very burdensome and costly in terms of time spent. Development costs are significantly higher due to the mismatch of the paradigms of data representation in objects and relational databases. Hibernate is a solution to the so-called Object Relational Projection for Java. The term object-relational projection refers to the technique of projecting (mapping) data from an object representation model to a relational representation model (and vice versa). See en.wikipedia.org/wiki/Object-relational_mapping for more details.
Important
Although using SQL is not necessary to use Hibernate, understanding basic concepts will play a good role in quickly and fully mastering Hibernate. The best help in mastering is understanding the principles of data modeling. The following links may be helpful.
Hibernate not only cares about projecting Java classes into database tables (as well as projecting basic Java types to SQL types), but also provides mechanisms for generating queries and data samples. It can significantly reduce development time, which was done in the old style by manually working with data using SQL and JDBC. The main goal of Hibernate architectural design is to save the developer from the daily tasks of working with database data by eliminating the need to write your own logic for working with data through SQL and JDBC. However, unlike other persistence solutions, Hibernate does not hide your ability to use the full power of SQL, and ensures that your investment in relational technology and knowledge is still valid.
Hibernate may not be the best solution for applications that store all their business logic in stored procedures, it is more suitable for object-oriented models and logic in the middle (business) layer of an application written in Java. However, Hibernate can certainly help you get rid of or encapsulate the logic of a specific SQL code, as well as cope with the daily tasks of translating the results of your queries from a table view into an object graph.
1. Access to the database
1.1. Connection
Hibernate connects to the database on behalf of your application. The connection can be carried out through various mechanisms, namely:
- Built-in connection pool
- javax.sql.DataSource
- Connection pools, you can also use third-party open source solutions for pools:
- c3p0
- proxool
- Application-created JDBC connections. This is not a recommended approach and the only reason for using it is to work with legacy environments.
Important
The built-in connection pool is not designed to work in a “combat” environment.
Hibernate receives JDBC connections as needed through the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface . Applications can also provide their implementations of the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface to define a custom approach for providing connections to Hibernate. (From another connection pool, for example)
1.1.1. Configuration
You can configure the connection to the database using the property file, via the XML deployment descriptor, or programmatically.
Example 1.1 hibernate.properties for 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 to connect to the embedded HSQL database
org.hsqldb.jdbcDriver jdbc:hsqldb:hsql://localhost sa 1 org.hibernate.dialect.HSQLDialect thread org.hibernate.cache.internal.NoCacheProvider true update
1.1.1.1. Software configuration
An instance of the org.hibernate.cfg.Configuration object represents a complete set of database mapping types. Object org.hibernate.cfg.Configuration creates immutabelny object org.hibernate.SessionFactory , and compiles mapping of various XML-files. You can specify files for mapping directly, or Hibernate can find them for you.
Example 1.3 Specifying files for mapping directly
You can get the org.hibernate.cfg.Configuration object by creating it and specifying XML documents for mapping directly. If the mapping files are in the classpath, use the addResource () method.
Configuration cfg = new Configuration()
.addResource("Item.hbm.xml")
.addResource("Bid.hbm.xml");
Example 1.4 Hibernate finds files for you.
The addClass () method tells Hibernate to look for mapping files through the classpath based on the class name, while saving you the trouble of specifying the file names yourself. In the following example, he 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 programmatically configure Hibernate
- Passing an instance of java.util.Properties to Configuration.setProperties ().
- Setting a system property using java -Dproperty = value
1.1.2. Getting JDBC Connection
After you configure the basic properties of the jdbc-the Hibernate , you can use the method openSession class org.hibernate.SessionFactory to open sessions. Sessions will open JDBC connections on demand based on the configuration provided.
Example 1.6 Opening session
Session session = sessions.openSession();
Hibernate core jdbc properties
- hibernate.connection.driver_class
- hibernate.connection.url
- hibernate.connection.username
- hibernate.connection.password
- hibernate.connection.pool_size
1.2. Connection pooling
The internal connection pooling algorithm in Hibernate is fairly rudimentary, and is needed, for the most part, for development and testing. Use third-party (3 rd party) pools for better performance and stability. To use the 3 rd party pool, replace the value of the hibernate.connection.pool_size property with the specifics of your selected pool. This will disable the use of the built-in Hibernate pool.
1.2.1. Pooling with c3p0
C3P0 is the open source JDBC connection pool distributed with Hibernate in the lib / directory. Hibernate will use its own org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider to pool connections when setting the hibernate.c3p0 properties. *
Important configuration properties for c3p0
- hibernate.c3p0.min_size
- hibernate.c3p0.max_size
- hibernate.c3p0.timeout
- hibernate.c3p0.max_statements
1.2.2. Proxool Pooling
Proxool is another open source pool distributed with Hibernate in the lib / directory. Hibernate will use its own org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider to pool connections when configured with hibernate.proxool. *. Unlike c3p0, proxool requires some additional settings, which are described in the documentation available at proxool.sourceforge.net/configure.html .
Table 1.1. Important configuration properties for the Proxool connection pool
Property | Description |
---|---|
hibernate.proxool.xml | Configure the Proxool provider using the specified XML file (.xml is added automatically) |
hibernate.proxool.properties | Configure the Proxool provider using the specified property file (.properties is added automatically) |
hibernate.proxool.existing_pool | Configure Proxool provider from an existing pool |
hibernate.proxool.pool_alias | Proxool pool alias. Needed. |
1.2.3. Getting Connections from an Application Server, via JNDI
To use Hibernate inside an application server, configure Hibernate to receive connections from javax.sql.Datasource registered in JNDI by setting at least one of the following properties:
Important properties for JNDI data sources
- hibernate.connection.datasource (required)
- hibernate.jndi.url
- hibernate.jndi.class
- hibernate.connection.username
- hibernate.connection.password
JDBC connections received from a JNDI data source automatically participate in container-managed application server transactions.
1.2.4. Other connection configuration
You can pass arbitrary connection properties by adding hibernate.connection in front of them . For example, to specify the charSet property, use the name hibernate.connection.charSet .
You can define your strategy for receiving JDBC connections by implementing the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface and specifying your custom implementation using the hibernate.connection.provider_class property
1.2.5. Optional configuration properties
In addition to the properties listed above, Hibernate includes many other parameters. See a more detailed list at http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html_single/ .
1.3. Dialects
Although SQL is relatively standardized, each DBMS vendor uses its own subset of supported syntaxes. This has another term called a dialect. Hibernate supports various dialect variations through the org.hibernate.dialect.Dialect class and various subclasses for each vendor dialect.
Table 1.2. Supported DBMS dialects

1.3.1. Indicate the dialect to use.
The developer can manually specify the dialect to use by specifying the appropriate subclass name org.hibernate.dialect.Dialect in the hibernate.dialect property .
1.3.2. Dialect resolution
Assuming in advance that org.hibernate.service.jdbc.connections.spi.ConnectionProvider has been configured, Hibernate will try to automatically detect the dialect based on the java.sql.DatabaseMetaData obtained from the java.sql.Connection object , which in turn is obtained from org. hibernate.service.jdbc.connections.spi.ConnectionProvider .
This functionality is provided by instances of org.hibernate.service.jdbc.dialect.spi.DialectResolver registered with the framework itself. Hibernate comes with a standard recognition set. If your application requires additional dialect recognition capabilities, it is possible to register a custom implementationorg.hibernate.service.jdbc.dialect.spi.DialectResolver , as shown below
Registered implementations of org.hibernate.service.jdbc.dialect.spi.DialectResolver are added to the internal resolver list so that they take precedence over previously registered resolvers , as well as over the standard.
1.4. Automatic circuit generation with SchemaExport
SchemaExport is a Hibernate utility that generates DDL scripts from your mapping files. The generated schema includes referential integrity constraints, primary and foreign keys for entities and collection tables. It also creates tables for sequences and projected identity generators.
Important
You must specify the SQL dialect through the hibernate.dialect property when using this utility, since the DDL itself is specific to each vendor. See details in Section 1.3, “Dialects” .
Before Hibernate can generate your schema, you must customize your mapping files.
1.4.1. Customizing the mapping files
Hibernate provides a number of elements and attributes for your mapping files. They are listed in Table 1.3, “Elements and Attributes Provided for Customizing Mapping Files,” and the 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 | Value type | Description |
---|---|---|
length | number | Column length |
precision | number | Decimal precision column |
scale | number | Decimal column scale |
not-null | true or false | Can a column contain null values |
unique | true or false | Does the column contain only unique values |
index | string | Multi-column index name |
unique-key | string | Name of multi-column uniqueness constraint |
foreign-key | string | Foreign key constraint name generated for associations. It refers to |
sql-type | string | Overrides the default column type. This applies only to the item. |
default | string | The default value for the column |
check | string | SQL constraints are either per column or table |
Procedure 1.1. Customization of the scheme
1. Setting the length, accuracy, and scale of the mapping elements.
Many mapping elements define optional attributes, such as length , precision , and scale .
2. Setting not-null, UNIQUE, unique-key attributes.
not-null and UNIQUE attributes generate table column constraints.
The unique-key attribute groups columns into a single uniqueness constraint. The attribute overrides the name of any generated uniqueness constraint.
3. Setting the index and foreign-key attributes.
The index attribute indicates the name of the index to create it using the projected column or columns. You can group several columns by one index, indicating in each of them the name of the same index.
The foreign key attribute overrides the name of any generated foreign key constraint.
4. Installation of subsidiaries
Many mapping elements allow the use of child
5. Setting the default attribute.
The default attribute is the default value for the column. Add a value to the projected property before saving a new instance of the class.
6. Установка атрибута sql-type.
Используйте атрибут sql-type для переопределения маппинга по-умолчанию для типов Java на типы SQL.
7. Установка атрибута check.
Используйте атрибут check для указания ограничения check.
...
8.Добавление
Используйте элемент
Current customers only
...
1.4.2. Запуск инструмента SchemaExport
Инструмент SchemaExport записывает DDL-скрипт в стандартный поток вывода, исполняет DDL, или и то, и другое сразу.
Пример 1.7. Синтаксис SchemaExport
java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files
Таблица 1.4. Опции SchemaExport
Опция | Описание |
---|---|
--quiet | Не выводить скрипт в стандартный поток вывода |
--drop | Только удалять таблицы |
--create | Только создавать таблицы |
--text | Не экспортировать в БД |
--output=my_schema.ddl | Вывести скрипт в указанный файл |
--naming=eg.MyNamingStrategy | NamingStrategy Choice |
--namingdelegator = eg.MyNamingStrategyDelegator | Choice NamingStrategyDelegator |
--config = hibernate.cfg.xml | Reading Hibernate configuration from XML file |
--properties = hibernate.properties | Reading database properties from the specified file |
--format | Neat SQL formatting |
--delimiter =; | Line separator |
Important
The --naming and --namingdelegator options should not be used together
Example 1.8 Embedding SchemaExport in your application
Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);