Hibernate parameter configuration

Source: Internet
Author: User
Tags postgresql org sybase

 

In J2ee applications, if the Hibernate framework is used, the ing between database entities and Java entity classes can be automatically established, which greatly facilitates Java programs to access and operate persistent objects, this significantly improves enterprise application development efficiency and reduces the dependency between Java programs and backend databases.

However, if you are not careful with the operation, the ing relationship may be incomplete (especially when a foreign key link exists), causing a Bug in the program when accessing the database object. In this case, you can configure parameters so that Hibernate can output corresponding SQL statements to the console each time it needs to query records from the database or insert or update database records, so as to understand specific database operations and better program debugging.

The method is:
1. Open the hibernate. cfg. xml file editing interface, click the Add button in the Properties window, and select the Show_ SQL parameter. The input value is True. For example:

 

2. Save hibernate. cfg. xml.

Then, run your program again and the corresponding SQL statements will be displayed in the console view.

In addition, if you add the following parameters in the same step, you can make the SQL statement more perfect:
1) parameter: format_ SQL = true makes the SQL statement format more beautiful and unified;
2) parameter: use_ SQL _comments = true: automatically injects comments into SQL statements to increase readability.
Is an example of the output result:

 

In addition, Hibernate also has many parameters. By reasonably configuring these parameters, we can improve the efficiency of objects in the Hibernate framework and optimize J2ee applications.
These parameters are as follows:
Java, IdeaGrace, web, development, technology, communication, tutorial-http://www.ideagrace.com/

Parameter usage
Hibernate. dialect A Hibernate Dialect class name allows Hibernate to generate optimized SQL statements for specific relational databases. The value is full. classname. of. Dialect.
Hibernate. show_ SQL outputs all SQL statements to the console. Another option is to set the log category org. hibernate. SQL to debug. Eg. true | false
Hibernate. format_ SQL prints more beautiful SQL statements in log and console. Value: true | false
Hibernate. default_schema attaches the given schema/tablespace to the table name with a non-fully qualified name in the generated SQL statement. The value SCHEMA_NAME
Hibernate. default_catalog in the generated SQL, attaches the given catalog to the table name with a non-fully qualified name. The value of CATALOG_NAME
After hibernate. session_factory_name SessionFactory is created, it is automatically bound to the JNDI with this name. The value of this name is jndi/composite/name.
Hibernate. max_fetch_depth sets the maximum depth for the outer join fetch tree of one-way join (one-to-one, multiple-to-one. if the value is 0, the default outer connection is disabled. the recommended value range is 0 to 3.
Hibernate. default_batch_fetch_size is the default quantity for batch capturing associated with Hibernate. The recommended values are 4, 8, and 16.
Hibernate. default_entity_mode specifies the default object expression mode for all sessions opened in this SessionFactory. The value is dynamic-map, dom4j, and pojo.
Hibernate. order_updates forces Hibernate to sort SQL updates by the primary key of the updated data. This will reduce the deadlock of transactions in High-concurrency systems. Value: true | false
Hibernate. generate_statistics if enabled, Hibernate collects statistical data that helps performance adjustment. Set this parameter to true | false
If hibernate. use_identifer_rollback is enabled, the ID attribute generated when the object is deleted will be reset to the default value. The value is true | false
If hibernate. use_ SQL _comments is enabled, Hibernate will generate comments for debugging in SQL. The default value is false. The value is true | false

Table 3.4. Hibernate JDBC and connection attributes

Attribute name usage
Hibernate. jdbc. fetch_size is a non-zero value that specifies the size of the number of JDBC captures (CALL Statement. setFetchSize ()).
Non-zero value of hibernate. jdbc. batch_size, which allows Hibernate to use batch update of JDBC2. The value range is 5 to 30.
Hibernate. jdbc. batch_versioned_data if you want your JDBC driver to return the correct row count from executeBatch (), set this attribute to true (enabling this option is usually safe ). at the same time, Hibernate uses batch DML for automatically versioning data. the default value is false. eg. true | false
Hibernate. jdbc. factory_class select a custom Batcher. Most applications do not need this Configuration Attribute. eg. classname. of. Batcher
Hibernate. jdbc. use_scrollable_resultset allows Hibernate to use the rolling result set of JDBC2. this option is necessary only when you use the JDBC connection provided by the user. Otherwise, Hibernate uses the connected metadata. value: true | false
Hibernate. jdbc. use_streams_for_binary uses stream (system-level Attribute) When JDBC reads/writes binary (binary) or serializable (serializable) types. The value is true | false
Hibernate. jdbc. use_get_generated_keys after data is inserted into the database, JDBC3 PreparedStatement. getGeneratedKeys () can be used to obtain the key (key) generated by the database ). JDBC3 + driver and JRE1.4 + are required. If your database driver encounters problems when using the Hibernate standard generator, set this value to false. by default, the connected metadata is used to determine the drive capability. value: true | false
Hibernate. connection. provider_class: Custom ConnectionProvider class name, which is used to provide JDBC connection to Hibernate. Value: classname. of. ConnectionProvider
Hibernate. connection. isolation sets the JDBC transaction isolation level. view java. SQL. connection to understand the specific meaning of each value, but note that most databases do not support all isolation levels. values: 1, 2, 4, and 8
Hibernate. connection. autocommit allows automatic submission of cached JDBC connections (autocommit) (not recommended). Value: true | false
Hibernate. connection. release_mode specifies when Hibernate releases the JDBC connection. by default, the JDBC connection is released only when the Session is explicitly closed or disconnected. for the JTA data source of the application server, you should use after_statement, so that the connection will be released automatically after each JDBC call. for non-JTA connections, it is reasonable to use after_transaction to release connections at the end of each transaction. auto selects after_statement for the jta and CMT transaction policies and after_transaction for the JDBC transaction policies. value: on_close | after_transaction | after_statement | auto
Hibernate. connection. <propertyName> pass the JDBC property propertyName to DriverManager. getConnection.
Hibernate. jndi. <propertyName> pass the property propertyName to the jndi InitialContextFactory.

Table 3.5. Hibernate cache attributes

Attribute name usage
The Class Name of CacheProvider customized by hibernate. cache. provider_class. Value: classname. of. CacheProvider
Hibernate. cache. use_minimal_puts optimizes the second-level cache to minimize write operations at the cost of frequent read operations. in Hibernate3, this setting is very useful for the cluster cache. It is enabled by default for the implementation of the cluster cache. value: true | false
Hibernate. cache. use_query_cache allows you to query the cache. Some queries still need to be set to cache. The value is true | false
Hibernate. cache. use_second_level_cache can be used to completely disable the use of second-level cache. For classes that are specified in the class ing definition, the second-level cache is enabled by default. The value is true | false
Hibernate. cache. query_cache_factory defines the class name for implementing the QueryCache interface. The default value is the built-in StandardQueryCache. The value is classname. of. QueryCache.
Hibernate. cache. region_prefix prefix of the second-level cache region name. Value: prefix
Hibernate. cache. use_structured_entries forces Hibernate to store data in the second-level cache in a more user-friendly format. The value is true | false

Table 3.6. Hibernate transaction attributes

Attribute name usage
Hibernate. transaction. factory_class: A Class Name of TransactionFactory. It is used for Hibernate Transaction API (JDBCTransactionFactory by default). Value: classname. of. TransactionFactory
Jta. UserTransaction: a jndi name used by JTATransactionFactory to obtain JTA UserTransaction from the application server. Value: jndi/composite/name
Hibernate. transaction. manager_lookup_class: A class name for TransactionManagerLookup-This class is required when JVM-level caching is used or when the hilo generator is used in the JTA environment. The value is classname. of. TransactionManagerLookup.
If hibernate. transaction. flush_before_completion is enabled, the session will be automatically cleaned (flush) after the transaction is completed ). Now it is better to use automatic session context management. Value: true | false
If hibernate. transaction. auto_close_session is enabled, the session will be automatically closed after the transaction is completed. Now it is better to use automatic session context management. Value: true | false

Table 3.7. Other attributes

Attribute name usage
Hibernate. current_session_context_class specifies a (custom) Policy for the "current" Session. Eg. jta | thread | custom. Class
Hibernate. query. factory_class select the implementation of the hql parser. Value org. hibernate. hql. ast. ASTQueryTranslatorFactory or org. hibernate. hql. classic. ClassicQueryTranslatorFactory
Hibernate. query. substitutions maps the symbols in the Hibernate query to the symbols in the SQL query (the symbols may be the function name or constant name). Value: hqlLiteral = SQL _LITERAL, hqlFunction = SQLFUNC
Hibernate. hbm2ddl. auto automatically checks the database structure when creating SessionFactory, or exports the DDL of the database schema to the database. when you use create-drop to explicitly close SessionFactory, the database schema will be dropped. value: validate | update | create-drop
Hibernate. cglib. use_reflection_optimizer enables CGLIB to replace runtime reflection mechanism (system-level Attribute ). reflection mechanisms are sometimes useful when division of errors. note that, even if you disable this optimization, Hibernate still needs CGLIB. you cannot go to hibernate. cfg. set this attribute in xml. value: true | false

3.4.1. SQL Dialect
You should always use hibernate for your database. set the dialect attribute to the correct org. hibernate. dialect. dialect subclass. if you specify a dialect, Hibernate uses reasonable default values for the attributes listed above, saving you the effort to manually specify them.

Table 3.8. Hibernate SQL dialect (hibernate. dialect)

RDBMS Dialect
DB2 org. hibernate. dialect. DB2Dialect
DB2 AS/400 org. hibernate. dialect. DB2400Dialect
DB2 OS390 org. hibernate. dialect. DB2390Dialect
PostgreSQL org. hibernate. dialect. PostgreSQLDialect
MySQL org. hibernate. dialect. MySQLDialect
MySQL with InnoDB org. hibernate. dialect. MySQLInnoDBDialect
MySQL with MyISAM org. hibernate. dialect. MySQLMyISAMDialect
Oracle (any version) org. hibernate. dialect. OracleDialect
Oracle 9i/10g org. hibernate. dialect. Oracle9Dialect
Sybase org. hibernate. dialect. SybaseDialect
Sybase Anywhere org. hibernate. dialect. SybaseAnywhereDialect
Microsoft SQL Server org. hibernate. dialect. SQLServerDialect
Sap db org. hibernate. dialect. SAPDBDialect
Informix org. hibernate. dialect. InformixDialect
HypersonicSQL org. hibernate. dialect. HSQLDialect
Ingres org. hibernate. dialect. IngresDialect
Progress org. hibernate. dialect. ProgressDialect
Mckoi SQL org. hibernate. dialect. MckoiDialect
Interbase org. hibernate. dialect. InterbaseDialect
Pointbase org. hibernate. dialect. PointbaseDialect
FrontBase org. hibernate. dialect. FrontbaseDialect
Firebird org. hibernate. dialect. FirebirdDialect

Table 3.9. Hibernate log categories

CATEGORY Function
Org. hibernate. SQL records logs when all SQL DML statements are executed.
Org. hibernate. type logs for all JDBC Parameters
Org. hibernate. tool. hbm2ddl records logs when all SQL DDL statements are executed.
Org. hibernate. pretty logs the status of all the entities associated with it (up to 20) during session cleaning (flush ).
Org. hibernate. cache is the activity log of all level-2 caches.
Org. hibernate. transaction is the transaction-related activity log.
Org. hibernate. jdbc records all JDBC resources.
Org. hibernate. hql. AST records the AST analysis logs of HQL and SQL during resolution query.
Org. hibernate. secure logs for JAAS authentication requests
Org. hibernate logs any Hibernate-related information (the amount of information is large, but it is very helpful for troubleshooting)

Table 3.10. JTA TransactionManagers

Transaction factory Application Server
Org. hibernate. transaction. JBossTransactionManagerLookup JBoss
Org. hibernate. transaction. WeblogicTransactionManagerLookup Weblogic
Org. hibernate. transaction. WebSphereTransactionManagerLookup WebSphere
Org. hibernate. transaction. WebSphereExtendedJTATransactionLookup WebSphere 6
Org. hibernate. transaction. OrionTransactionManagerLookup Orion
Org. hibernate. transaction. ResinTransactionManagerLookup Resin
Org. hibernate. transaction. JOTMTransactionManagerLookup JOTM
Org. hibernate. transaction. JOnASTransactionManagerLookup JOnAS
Org. hibernate. transaction. JRun4TransactionManagerLookup JRun4
Org. hibernate. transaction. BESTransactionManagerLookup Borland ES

 

(End)

Use p6spy to completely display hibernate SQL statements
Although the show_ SQL option is available in hibernate, most of the displayed statements are similar.
Select * from xxx where value =?
But sometimes we need a complete SQL statement. What should we do? You can use P6SPY to complete this task.

P6spy is an open-source software that can trace any database operations generated by applications using jdbc. It is particularly suitable for monitoring the SQL statements generated by the ejb server.
Official Website: http://www.p6spy.com/
Currently, p6spy is applicable to jboss, atg, orion, jonas, iplanet, weblogic, websphere, resin and tomcat.

The following describes how to install p6spy on a tomcat application:
(1) download the zip package at http://www.p6spy.com/download.html
(2) decompress the p6spy. jar spy. properties files.
(3) Put p6spy. jar into the WEB-INF/lib directory of the application, put spy. properties into the WEB-INF/classes directory
(4) Modify spy. properties

Realdriver = com. mysql. jdbc. Driver: remove the # above this line
Logfile = c:/spy. log modify a log file name

(5) Modify hibernate. xml and set connection. driver_class to com. p6spy. engine. spy. P6SpyDriver.
(6) Restart tomcat
(7) The spy. log in c:/records the database access.

 

 

-----------------------------------------

1. Download the attachment's p6psy. jar and spy. properties files.

2. Put p6spy. jar under the lib directory of the application, put spy. properties under the WEB-INF \ classes directory

3. Modify row 41st of the spy. properties sample. Change to required database information
Modify row 54th of the spy. properties sample. Change to required database information

Modify the 168th rows of the spy. properties sample and put spy. log to a better location:
Example: logfile = E:/spy. log

4. Solve the driver Loading Problems
If
The database driver name of your program is a real driver in spy. properties, but it has been loaded before p6spy. p6spy will not wrap these connections. either prevent the driver from loading, or try setting 'deregisterdrivers' to true in spy. properties
Change deregisterdrivers = false in the spy. properties file to deregisterdrivers = true, and run the command again.

5. Configure the following in the spring configuration file:

<! -- P6SPY dataSource target -->
<Bean id = "dataSourceTarget" class = "org. springframework. jdbc. datasource. DriverManagerDataSource">
<Property name = "driverClassName"
Value = "oracle. jdbc. OracleDriver"/>
<Property name = "url"
Value = "jdbc: oracle: thin: @ localhost: 1521: testdb"/>
<Property name = "username" value = "tet"/>
<Property name = "password" value = "test"/>
</Bean>

<! -- DataSource -->
<Bean id = "cece4develop" class = "com. p6spy. engine. spy. P6DataSource" destroy-method = "close">
<Constructor-arg>
<Ref local = "dataSourceTarget"/>
</Constructor-arg>
</Bean>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.