In J2ee application, if Hibernate framework, it can automatically create a mapping between database entities and Java entity class, greatly facilitate the Java program persistent object access and operation, thereby significantly improve application development efficiency, reduce the Java program and background database dependence.
(Especially when there is a foreign key link) However, if sometimes careless operation, may result in incomplete mapping relationship, caused when the program has access to database objects Bug. In this case, parameters can be configured, so that each time required Hibernate each inserted from a record database query or update the database record, the output of the corresponding SQL statement to the console, so that for specific database operations, better procedures debugging.
The method is:
1, opens the hibernate.cfg.xml file editing interface, in the Properties window, the click the Add button, select Show_SQL parameter, enter a value of True. As shown below:
2, save hibernate.cfg.xml.
Then, run your program again, in the console view will display the corresponding SQL statement.
Further, according to the same procedure, were added the following parameters, allows SQL statements more perfect:
1) Parameters: format_sql = true that the SQL statement is more beautiful uniform;
2) parameters: use_sql_comments = true that the SQL statement automatic injection annotations, readability
Below is an example of output results:
In addition, there are many parameters Hibernate, through the rational allocation of these parameters can improve the efficiency Hibernate framework objects, enabling the optimization of J2ee applications.
These parameters are as follows:
the Java, IdeaGrace, Web, development, technology, communication, tutorials - http://www.ideagrace.com/
Parameter Purpose
hibernate.dialect a Hibernate Dialect class name allows Hibernate to generate SQL optimized for a particular relational database. The value full.classname.of.Dialect
the hibernate.show_sql all SQL statements to console. There is a further option is to org .hibernate.SQL the log category to debug. to true EG |. false
hibernate.format_sql Pretty print the SQL in the log and console. The value to true | to false
hibernate.default_schema in the generated SQL, given schema / tablespace attached to the non-fully qualified name table values SCHEMA_NAME.
Hibernate.default_catalog in the generated SQL, given catalog additional in the non-fully qualified table name. CATALOG_NAME value
after hibernate.session_factory_name SessionFactory created, will automatically bound to this name in JNDI. value of the JNDI / Composite / name
hibernate.max_fetch_depth unidirectional association (one to one, many to one) outer join fetching (outer join fetch) sets the maximum depth of the tree. a value of 0 disables default outer join fetching. the value between 0 and this parameter. 3
hibernate.default_batch_fetch_size as Hibernate is batch fetching set the default number. the value recommended value of 4, 8, and 16
hibernate.default_entity_mode by the Session SessionFactory open all specify the default mode for entity representation value-Map Dynamic, the dom4j, POJO
hibernate.order_updates force Hibernate to update the primary key data, ordered as SQL update. Doing so would reduce transaction deadlocks in highly concurrent systems. The value to true | false
hibernate.generate_statistics If enabled, Hibernate will collect statistics useful for performance tuning of the value to true |. False
hibernate.use_identifer_rollback If enabled, generated when an object is deleted identifier properties will be reset to default values . the value to true | false
hibernate.use_sql_comments If enabled, Hibernate will generate comments in SQL information useful in debugging, defaults to false values true |. false
Table 3.4. Hibernate JDBC and connection (Connection) properties
Property name Purpose
hibernate.jdbc.fetch_size non-zero value, the JDBC fetch size (calls Statement.setFetchSize ()).
Hibernate.jdbc.batch_size non-zero value, allowing the use of Hibernate JDBC2 batch update value is recommended to take 5 value between 30
hibernate.jdbc.batch_versioned_data If you want your JDBC driver returns correct row counts from executeBatch (), then this property is set to true (enable this option is usually safe). At the same time, Hibernate will use automatic version of the data batch DML default value to true EG false |... false
. hibernate.jdbc.factory_class select a custom Batcher most applications do not need this configuration property classname.of.BatcherFactory EG..
Hibernate. . jdbc.use_scrollable_resultset allowed to use Hibernate JDBC2 scrollable result sets only when using user-supplied JDBC connection, this option is necessary, otherwise Hibernate uses connection metadata values to true |. false
hibernate.jdbc.use_streams_for_binary in use stream (Strea time (binary) or serializable (serializable) write binary type JDBC m) (system level property) value of true |. false
hibernate.jdbc.use_get_generated_keys After the data into the database, allowing the use of JDBC3 PreparedStatement.getGeneratedKeys () to get the key (key) generated by the database. Need JDBC3 + drive and JRE1.4 +, if your driver has problems with the Hibernate identifier generators, set this value to false. By default, using meta data connection to determine the driver capabilities. Take value to true | false
hibernate.connection.provider_class classname of a custom of ConnectionProvider, which provides JDBC connections to Hibernate values classname.of.ConnectionProvider.
hibernate.connection.isolation set JDBC transaction isolation level view java.sql.Connection. come for meaningful values, but note that most databases do not support all isolation levels. the value 1, 2, 4, 8
hibernate.connection.autocommit allowed to be cached JDBC connections enable auto-commit (autocommit) (not recommended .) value true | false
Hibernate hibernate.connection.release_mode specify when to release JDBC connections. By default, until it is explicitly closed Session or is disconnected, will release JDBC connections. JTA data source for the application server, use after_statement so after each JDBC calls, it will take the initiative to release the connection. for a non-JTA connection, it is reasonable to use after_transaction release the connection at the end of each transaction. auto JTA and CMT transaction strategies will select after_statement, for the JDBC transaction strategy select after_transaction value ON_CLOSE |. after_transaction | after_statement to | Auto
. hibernate.connection <propertyName> propertyName the property passed to the DriverManager.getConnection JDBC () to go.
hibernate.jndi <propertyName> transferring property to the JNDI InitialContextFactory propertyName go.
Table 3.5. Hibernate Cache Properties
Property name Purpose
hibernate.cache.provider_class CacheProvider custom class name. Value classname.of.CacheProvider
of hibernate.cache.use_minimal_puts read operation at the expense of frequent, optimizing to minimize secondary cache write operation. In the Hibernate3, this set of cluster cache is very useful in terms of the realization of the cluster caching is enabled by default values true |. false
. hibernate.cache.use_query_cache allow the query cache, individual queries still have to be set to the value true cacheable | false
hibernate.cache.use_second_level_cache can be used to completely disable the second level cache mapping definitions specify those classes in a <cache> class, second-level cache is enabled by default value to true |.. false
hibernate.cache.query_cache_factory from QueryCache implementation class name defined interface, defaults to the built-in StandardQueryCache. classname.of.QueryCache values
prefix hibernate.cache.region_prefix two cache region names. the value prefix
hibernate.cache.use_structured_entries force Hibernate more humane format data into the secondary cache values true |. false
Table 3.6. Hibernate Transaction Properties
Property name Purpose
hibernate.transaction.factory_class TransactionFactory a class name, for Hibernate Transaction API (defaults to JDBCTransactionFactory). The value classname.of.TransactionFactory
jta.UserTransaction a JNDI name, is used to obtain JTATransactionFactory JTA UserTransaction from the application server. value jndi / composite / name
class name of a TransactionManagerLookup hibernate.transaction.manager_lookup_class - when JVM-level cache, or when using hilo generator in a JTA environment in need of such values classname.of.TransactionManagerLookup.
hibernate.transaction. after flush_before_completion If enabled, session to complete the transaction is automatically cleaned (flush). Now better approach is to use an automatic session context management. Value true | false
after hibernate.transaction.auto_close_session If enabled, session to complete the transaction is automatically closed. Now better approach is to use an automatic session context management. Value true | false
Table 3.7 Other properties
Property name Purpose
hibernate.current_session_context_class as "current" Session specify a (custom) strategy. JTA EG |. the Thread | custom.Class
hibernate.query.factory_class choose to implement HQL parser or org.hibernate.hql.classic.ClassicQueryTranslatorFactory value org.hibernate.hql.ast.ASTQueryTranslatorFactory.
hibernate.query.substitutions the Hibernate query the symbols are mapped to SQL queries symbol (symbol might be function or literal names). value = SQL_LITERAL hqlLiteral, hqlFunction = SQLFUNC
hibernate.hbm2ddl.auto when the SessionFactory is created automatically check the database structure or schema of the database DDL exported to the database using the create-drop, when closed explicitly SessionFactory, the database schema values drop off the validate |.. Update | Create | Create-drop
hibernate.cglib.use_reflection_optimizer open CGLIB runtime instead of reflection (system . level properties) reflection is sometimes useful when debugging Note even if you close this optimization, Hibernate or need CGLIB you can not set this property in hibernate.cfg.xml value true |... false
3.4.1. SQL dialect
you should always hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database. If you specify a dialect, Hibernate will list some of the above property is used sensible defaults, eliminating the need for you to manually specify their effort.
Table 3.8. Hibernate SQL dialect (hibernate.dialect)
RDBMS 方言
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 Feature
org.hibernate.SQL to record them all SQL DML statements are executed log
org.hibernate.type parameters for all JDBC logging
org.hibernate.tool.hbm2ddl logging them in all SQL DDL statements executed
org. when the cleaning session hibernate.pretty (flush), is associated with all entities (up to 20) status logging
org.hibernate.cache secondary cache for all activity log
org.hibernate.transaction transaction related activities logging
org.hibernate.jdbc for all JDBC resource acquisition log
org.hibernate.hql.AST in resolution query when recording HQL and SQL AST analyze log
org.hibernate.secure JAAS authentication request to do log
org.hibernate do Hibernate logs for any relevant information (large amount of information, but very useful for troubleshooting)
表 3.10. JTA TransactionManagers
Transaction工厂类 应用程序服务器
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
(Finish)
Using hibernate p6spy complete display of SQL statements
, although there are options in show_sql hibernate, but it displayed the most similar statement
select * from xxx where value =?
But sometimes we need to get a complete SQL statement, how to do it? Use P6SPY to complete this task
p6spy is an open source software that can track any database operations using jdbc application generated. Especially suitable for monitoring sql statements ejb generated by the server.
Official Website: http://www.p6spy.com/
currently p6spy applicable application servers include jboss, atg, orion, jonas, iplanet, weblogic, websphere, resin and tomcat.
Let me explain the steps p6spy on tomcat applications installed:
(1) http://www.p6spy.com/download.html , download the zip package
(2) p6spy.jar spy.properties extract the two files
(3 ) into the p6spy.jar application WEB-INF / lib directory, spy.properties into WEB-INF / classes directory
(4) modified spy.properties
realdriver = com.mysql.jdbc.Driver remove these front line #
logfile = c: /spy.log you need to modify a log file name
(5) modify hibernate.xml, modify connection.driver_class value com.p6spy .engine.spy.P6SpyDriver
(. 6) to restart Tomcat
(. 7) so that c: spy.log / visits recorded in the database.
-----------------------------------------
1. Download the file attachments p6psy.jar and spy.properties
2. lib directory p6spy.jar into the application will spy.properties put under WEB-INF \ classes directory
3. Modify line 41 spy.properties sample. Information into the database need
to modify line 54 spy.properties sample. The required information into the database
Spy.properties modify the sample line 168, the spy.log place relatively easy to find here:
For example: logfile = E: /spy.log
4. Driver loading problems have solutions
if spy.log appeared
database-driven program of your name 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
please spy.properties documents in the deregisterdrivers = false changed deregisterdrivers = true, you can re-run.
5. In the spring configuration file is as follows:
<!-- 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="dataSource4develop" class="com.p6spy.engine.spy.P6DataSource" destroy-method="close">
<constructor-arg>
<ref local="dataSourceTarget"/>
</constructor-arg>
</bean>
Reproduced in: https: //www.cnblogs.com/coconut_zhang/archive/2008/11/27/1342432.html