📜 ⬆️ ⬇️

Hibernate Developer Documentation - Chapter I. Database Access

I present to you the translation of the first chapter of the official documentation Hibernate .

Article translation is relevant for the version Hibernate 4.2.19.Final

Next chapter - Hibernate Developer Documentation - Chapter II. Transactions and multithreading
')
Content
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 via JNDI
1.2.4. Other on connection configuration
1.2.5. Optional configuration properties
1.3. Dialects
1.3.1. Specifying a dialect to use
1.3.2. Dialect resolution
1.4. Automatic schema generation with Schema Export
1.4.1. Customizing the mapping files
1.4.2. Run the SchemaExport tool

Foreword


Working with both object-oriented software, and with relational databases (hereinafter referred to as database, comment perev.) Can be very burdensome and costly in terms of time spent. Development costs are significantly higher due to the discrepancy between 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 the object model of the view to the relational model of the view (and vice versa). See en.wikipedia.org/wiki/Object-relational_mapping for more details.

Important
Although it is not necessary to master SQL well to use Hibernate, understanding basic concepts will play a good role in the rapid and complete mastery of Hibernate. The best help in mastering is understanding the principles of data modeling. Information on the following links may be helpful.


Hibernate not only takes care of 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 in the old style was carried out by manual work with data using SQL and JDBC. The main goal of Hibernate architectural design is to rid the developer of the daily tasks of working with database data, by eliminating the need to write their own data manipulation logic through SQL and JDBC. However, unlike other persistence solutions, Hibernate does not hide from you the ability to use the full power of SQL, and ensures that your investments in relational technology and knowledge are 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 the average logic (business) layer of an application written in Java. However, Hibernate can definitely help you get rid of or encapsulate the logic of a specific SQL code, as well as cope with everyday tasks of translating the results of your queries from a table view into a graph of objects.

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 kinds of mechanisms, namely:

Important
The built-in pool of compounds is not designed to work in a “combat” environment.

Hibernate receives JDBC connections as needed via the org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface. Applications can also provide their org.hibernate.service.jdbc.connections.spi.ConnectionProvider interface implementations to define a custom approach to providing connections to Hibernate. (From another connection pool, for example)

1.1.1. Configuration


You can configure a connection to the database using a property file, an 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 for connecting to an embedded 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. Software configuration


An instance of the org.hibernate.cfg.Configuration object represents the complete set of database mapping types. The org.hibernate.cfg.Configuration object creates an immutable org.hibernate.SessionFactory object, and compiles mappings from various XML files. You can specify mapping files directly, or Hibernate can find them for you.

Example 1.3. Specifying mapping files directly

You can get the org.hibernate.cfg.Configuration object by creating it and specifying the XML documents for mapping directly. If the files for mapping 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 search for mapping files through the classpath, based on the class name, while eliminating the need to specify the names of the files yourself. 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 Hibernate Software Configuration Methods


1.1.2. Getting JDBC connection


After you configure the Hibernate jdbc Basic properties , you can use the openSession method of the org.hibernate.SessionFactory class to open sessions. Sessions will open on-demand JDBC connections based on the provided configuration.

Example 1.6. Opening session

 Session session = sessions.openSession(); 

Basic jdbc properties of hibernate


1.2. Connection pooling


Hibernate's internal pooling algorithm is rather 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 to match the specifics of your chosen pool. This will disable the use of the built-in Hibernate pool.

1.2.1. Pooling with c3p0


C3P0 is an open source pool of JDBC connections distributed with Hibernate in the lib / directory. Hibernate will use its own org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider for pooling connections when setting up hibernate.c3p0. * Properties

Important configuration properties for c3p0


1.2.2. Pooling with Proxool


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 with the appropriate configuration of hibernate.proxool. *. Unlike c3p0, proxool requires some additional configuration options, which are described in the documentation available at proxool.sourceforge.net/configure.html .

Table 1.1. Important configuration properties for the Proxool connection pool
PropertyDescription
hibernate.proxool.xmlConfigure the Proxool provider using the specified XML file (.xml is added automatically)
hibernate.proxool.propertiesConfigure the Proxool provider using the specified property file (.properties are automatically added)
hibernate.proxool.existing_poolConfigure a Proxool provider from an existing pool.
hibernate.proxool.pool_aliasThe proxool pool alias. Required

1.2.3. Getting connections from the application server via JNDI


To use Hibernate inside an application server, configure Hibernate to get 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 the container-managed transactions of the application server.

1.2.4. Other on 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 getting 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 options. 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 database vendor uses its own subset of supported syntaxes. There is another term for this, called a dialect. Hibernate supports different variations of dialects through the org.hibernate.dialect.Dialect class and different subclasses for each vendor dialect.

Table 1.2. Supported DBMS dialects


1.3.1. Specifying a dialect to use


The developer can manually specify the dialect to use by specifying the desired 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 determine the dialect based on java.sql.DatabaseMetaData obtained from the java.sql.Connection object, which in turn comes from org. hibernate.service.jdbc.connections.spi.ConnectionProvider .
This functionality is provided by org.hibernate.service.jdbc.dialect.spi.DialectResolver instances registered with the framework itself. Hibernate comes with a standard set of recognitions. If your application requires additional dialect recognition, it is quite possible to register a custom implementation of org.hibernate.service.jdbc.dialect.spi.DialectResolver , as shown below
Registered org.hibernate.service.jdbc.dialect.spi.DialectResolver implementations are added to the internal list of resolvers, so that they take precedence over previously registered resolvers as well as standard ones.

1.4. Automatic schema 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 (sequences) and projected id generators (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 Section 1.3, “Dialects” for details.

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

Table 1.3. Elements and attributes provided for customizing mapping files
NameValue typeDescription
lengthnumberColumn length
precisionnumberDecimal column accuracy
scalenumberDecimal column
not-nulltrue or falseCan the column contain null values
uniquetrue or falseDoes the column contain only unique values?
indexstringMulticolumn index name
unique-keystringName of multicolumn uniqueness constraint
foreign-keystringThe name of the foreign key constraint generated for associations.
This applies to <one-to-one>, <many-to-one>, <key>, and <many-to-many> elements. inverse = "true" are skipped by SchemaExport.
sql-typestringOverrides the default column type. This only applies to the <column> element.
defaultstringDefault value for column
checkstringSQL constraints (SQL check constraint) either per column or per table

Procedure 1.1. Customization scheme

1. Setting the length, accuracy, and scale of the mapping elements.

The set of mapping elements defines optional attributes, such as length , precision , and scale .
 <property name="zip" length="5"/> <property name="balance" precision="12" scale="2"/> 


2. Setting not-null, UNIQUE, unique-key attributes.

not-null and UNIQUE attributes generate constraints on table columns.
The unique-key attribute groups the columns into a single unique constraint. The attribute overrides the name of any generated unique 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. Setting the index and foreign-key attributes.

The index attribute specifies the name of the index to create it using the projected column or columns. You can group several columns by one index, specifying the name of the same index in each of them.
The foreign key attribute overrides the name of any generated foreign key constraint.
 <many-to-one name="bar" column="barId" foreign-key="FKFooBar"/> 


4. Installation of child <column> elements.

Many elements of mapping allow the use of child <column> elements. This is useful for mapping types that include 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. Setting the default attribute.

The default attribute is the default value for the column. Add a value to the projected property before saving the new instance of the 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. Setting the sql-type attribute.
Use the sql-type attribute to override the default mapping for Java types for SQL types.
 <property name="balance" type="float"> <column name="balance" sql-type="decimal(13,3)"/> </property> 


7. Setting 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. Run the SchemaExport tool


The SchemaExport tool writes the DDL script to the standard output stream, executes the DDL, or both at once.
Example 1.7. SchemaExport syntax
 java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files 

Table 1.4. SchemaExport Options
OptionDescription
--quietDo not output script to standard output.
--dropDelete tables only
--createOnly create tables
--textDo not export to DB
--output = my_schema.ddlPrint the script to the specified file.
--naming = eg.MyNamingStrategyNamingStrategy selection
--namingdelegator = eg.MyNamingStrategyDelegatorNamingStrategyDelegator selection
--config = hibernate.cfg.xmlReading the hibernate configuration from an xml file
--properties = hibernate.propertiesReading database properties from the specified file
--formatSQL tidy formatting
--delimiter =;Row 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); 

Source: https://habr.com/ru/post/301384/


All Articles