3.4. 可选的配置属性

有大量属性能用来控制Hibernate在运行期的行为. 它们都是可选的, 并拥有适当的默认值.

Warning: some of these properties are "system-level" only. System-level properties can be set only via java -Dproperty=value or hibernate.properties. They may not be set by the other techniques described above.

表 3.3. Hibernate配置属性

属性名 用途
hibernate.dialect The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.

eg. full.classname.of.Dialect

In most cases Hibernate will actually be able to chose the correct org.hibernate.dialect.Dialect implementation to use based on the JDBC metadata returned by the JDBC driver.

hibernate.show_sql Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

eg. true | false

hibernate.format_sql Pretty print the SQL in the log and console.

eg. true | false

hibernate.default_schema Qualify unqualified table names with the given schema/tablespace in generated SQL.

eg. SCHEMA_NAME

hibernate.default_catalog Qualify unqualified table names with the given catalog in generated SQL.

eg. CATALOG_NAME

hibernate.session_factory_name The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created.

eg. jndi/composite/name

hibernate.max_fetch_depth Set a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching.

取值 建议在03之间取值

hibernate.default_batch_fetch_size Set a default size for Hibernate batch fetching of associations.

取值 建议的取值为4, 8, 和16

hibernate.default_entity_mode Set a default mode for entity representation for all sessions opened from this SessionFactory

取值dynamic-map, dom4j, pojo

hibernate.order_updates Force Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.

eg. true | false

hibernate.generate_statistics If enabled, Hibernate will collect statistics useful for performance tuning.

eg. true | false

hibernate.use_identifer_rollback If enabled, generated identifier properties will be reset to default values when objects are deleted.

eg. true | false

hibernate.use_sql_comments If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false.

eg. true | false


表 3.4. Hibernate JDBC和连接(connection)属性

属性名 用途
hibernate.jdbc.fetch_size A non-zero value determines the JDBC fetch size (calls Statement.setFetchSize()).
hibernate.jdbc.batch_size A non-zero value enables use of JDBC2 batch updates by Hibernate.

取值 建议取530之间的值

hibernate.jdbc.batch_versioned_data Set this property to true if your JDBC driver returns correct row counts from executeBatch() (it is usually safe to turn this option on). Hibernate will then use batched DML for automatically versioned data. Defaults to false.

eg. true | false

hibernate.jdbc.factory_class Select a custom org.hibernate.jdbc.Batcher. Most applications will not need this configuration property.

eg. classname.of.BatcherFactory

hibernate.jdbc.use_scrollable_resultset Enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user supplied JDBC connections, Hibernate uses connection metadata otherwise.

eg. true | false

hibernate.jdbc.use_streams_for_binary Use streams when writing/reading binary or serializable types to/from JDBC. *system-level property*

eg. true | false

hibernate.jdbc.use_get_generated_keys Enable use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+, set to false if your driver has problems with the Hibernate identifier generators. By default, tries to determine the driver capabilities using connection metadata.

eg. true|false

hibernate.connection.provider_class The classname of a custom org.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.

eg. classname.of.ConnectionProvider

hibernate.connection.isolation Set the JDBC transaction isolation level. Check java.sql.Connection for meaningful values but note that most databases do not support all isolation levels and some define additional, non-standard isolations.

eg. 1, 2, 4, 8

hibernate.connection.autocommit Enables autocommit for JDBC pooled connections (not recommended).

eg. true | false

hibernate.connection.release_mode Specify when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. For an application server JTA datasource, you should use after_statement to aggressively release connections after every JDBC call. For a non-JTA connection, it often makes sense to release the connection at the end of each transaction, by using after_transaction. auto will choose after_statement for the JTA and CMT transaction strategies and after_transaction for the JDBC transaction strategy.

eg. auto (default) | on_close | after_transaction | after_statement

Note that this setting only affects Sessions returned from SessionFactory.openSession. For Sessions obtained through SessionFactory.getCurrentSession, the CurrentSessionContext implementation configured for use controls the connection release mode for those Sessions. See 第 2.5 节 “上下文相关的(Contextual)Session”

hibernate.connection.<propertyName> Pass the JDBC property <propertyName> to DriverManager.getConnection().
hibernate.jndi.<propertyName> Pass the property <propertyName> to the JNDI InitialContextFactory.

表 3.5. Hibernate缓存属性

属性名 用途
hibernate.cache.provider_class The classname of a custom CacheProvider.

eg. classname.of.CacheProvider

hibernate.cache.use_minimal_puts Optimize second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations.

eg. true|false

hibernate.cache.use_query_cache Enable the query cache, individual queries still have to be set cachable.

eg. true|false

hibernate.cache.use_second_level_cache May be used to completely disable the second level cache, which is enabled by default for classes which specify a <cache> mapping.

eg. true|false

hibernate.cache.query_cache_factory The classname of a custom QueryCache interface, defaults to the built-in StandardQueryCache.

eg. classname.of.QueryCache

hibernate.cache.region_prefix A prefix to use for second-level cache region names.

eg. prefix

hibernate.cache.use_structured_entries Forces Hibernate to store data in the second-level cache in a more human-friendly format.

eg. true|false


表 3.6. Hibernate事务属性

属性名 用途
hibernate.transaction.factory_class The classname of a TransactionFactory to use with Hibernate Transaction API (defaults to JDBCTransactionFactory).

eg. classname.of.TransactionFactory

jta.UserTransaction A JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction from the application server.

eg. jndi/composite/name

hibernate.transaction.manager_lookup_class The classname of a TransactionManagerLookup - required when JVM-level caching is enabled or when using hilo generator in a JTA environment.

eg. classname.of.TransactionManagerLookup

hibernate.transaction.flush_before_completion If enabled, the session will be automatically flushed during the before completion phase of the transaction. Built-in and automatic session context management is preferred, see 第 2.5 节 “上下文相关的(Contextual)Session”.

eg. true | false

hibernate.transaction.auto_close_session If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and utomatic session context management is preferred, see 第 2.5 节 “上下文相关的(Contextual)Session”.

eg. true | false


表 3.7. 其他属性

属性名 用途
hibernate.current_session_context_class Supply a (custom) strategy for the scoping of the "current" Session. See 第 2.5 节 “上下文相关的(Contextual)Session” for more information about the built-in strategies.

eg. jta | thread | managed | custom.Class

hibernate.query.factory_class Chooses the HQL parser implementation.

eg. org.hibernate.hql.ast.ASTQueryTranslatorFactory or org.hibernate.hql.classic.ClassicQueryTranslatorFactory

hibernate.query.substitutions Mapping from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names, for example).

eg. hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

hibernate.hbm2ddl.auto Automatically validate or export schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

eg. validate | update | create | create-drop

hibernate.cglib.use_reflection_optimizer Enables use of CGLIB instead of runtime reflection (System-level property). Reflection can sometimes be useful when troubleshooting, note that Hibernate always requires CGLIB even if you turn off the optimizer. You can not set this property in hibernate.cfg.xml.

eg. true | false


3.4.1. SQL方言

你应当总是为你的数据库将hibernate.dialect属性设置成正确的 org.hibernate.dialect.Dialect子类. 如果你指定一种方言, Hibernate将为上面列出的一些属性使用合理的默认值, 为你省去了手工指定它们的功夫.

表 3.8. Hibernate SQL方言 (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

3.4.2. 外连接抓取(Outer Join Fetching)

如果你的数据库支持ANSI, Oracle或Sybase风格的外连接, 外连接抓取通常能通过限制往返数据库次数 (更多的工作交由数据库自己来完成)来提高效率. 外连接抓取允许在单个SELECTSQL语句中, 通过many-to-one, one-to-many, many-to-many和one-to-one关联获取连接对象的整个对象图.

hibernate.max_fetch_depth设为0能在全局 范围内禁止外连接抓取. 设为1或更高值能启用one-to-one和many-to-oneouter关联的外连接抓取, 它们通过 fetch="join"来映射.

参见第 19.1 节 “抓取策略(Fetching strategies)”获得更多信息.

3.4.3. 二进制流 (Binary Streams)

Oracle限制那些通过JDBC驱动传输的字节数组的数目. 如果你希望使用二进值 (binary)可序列化的 (serializable)类型的大对象, 你应该开启 hibernate.jdbc.use_streams_for_binary属性. 这是系统级属性.

3.4.4. 二级缓存与查询缓存

hibernate.cache为前缀的属性允许你在Hibernate中,使用进程或群集范围内的二级缓存系统. 参见第 19.2 节 “二级缓存(The Second Level Cache)”获取更多的详情.

3.4.5. 查询语言中的替换

你可以使用hibernate.query.substitutions在Hibernate中定义新的查询符号. 例如:

hibernate.query.substitutions true=1, false=0

将导致符号truefalse在生成的SQL中被翻译成整数常量.

hibernate.query.substitutions toLowercase=LOWER

将允许你重命名SQL中的LOWER函数.

3.4.6. Hibernate的统计(statistics)机制

如果你开启hibernate.generate_statistics, 那么当你通过 SessionFactory.getStatistics()调整正在运行的系统时,Hibernate将导出大量有用的数据. Hibernate甚至能被配置成通过JMX导出这些统计信息. 参考org.hibernate.stats中接口的Javadoc,以获得更多信息.