Hibernate 3.6.10.Final ²Î¿¼ÊÖ²á ÖÐÎÄ°æ

Hibernate

Hibernate.org Community Documentation

Configuration cfg = new Configuration()
    .addResource("Item.hbm.xml")

    .addResource("Bid.hbm.xml");
Configuration cfg = new Configuration()

    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);
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");
  1. 传一个 java.util.Properties 实例给 Configuration.setProperties()

  2. hibernate.properties 放置在类路径(classpath)的根目录下(root directory)。

  3. 通过 java -Dproperty=value 来设置系统(System)属性。

  4. hibernate.cfg.xml 中加入元素 <property>(稍后讨论)。

        
        SessionFactory
        
         sessions 
        
        =
        
         cfg
        
        .
        
        buildSessionFactory
        
        ();
      
        
        Session
        
         session 
        
        =
        
         sessions
        
        .
        
        openSession
        
        ();
        
         
        
        //
        
         open a 
        
        new
        
         
        
        Session
      
属性名 用途
hibernate.connection.driver_class JDBC driver class
hibernate.connection.url JDBC URL
hibernate.connection.username database user
hibernate.connection.password 数据库用户密码
hibernate.connection.pool_size maximum number of pooled connections

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.PostgreSQLDialect
属性名 用途
hibernate.connection.datasource 数据源 JNDI 名字
hibernate.jndi.url JNDI 提供者的 URL(可选)
hibernate.jndi.class JNDI InitialContextFactory(可选)
hibernate.connection.username 数据库用户(可选)
hibernate.connection.password 数据库密码(可选)

hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

警告

其中一些属性是"系统级(system-level)的"。系统级属性只能通过java -Dproperty=valuehibernate.properties 来设置,而不能用上面描述的其他方法来设置。

属性名 用途
hibernate.dialect 允许 Hibernate 针对特定的关系数据库生成优化的 SQL 的 org.hibernate.dialect.Dialect 的类名。
hibernate.show_sql 输出所有 SQL 语句到控制台。有一个另外的选择是把 org.hibernate.SQL 这个 log category设为 debug
hibernate.format_sql 在 log 和 console 中打印出更漂亮的 SQL。

例如:true | false

hibernate.default_schema 在生成的 SQL 中,将给定的 schema/tablespace 附加于非全限定名的表名上。

例如:SCHEMA_NAME

hibernate.default_catalog 在生成的 SQL 中,将给定的 catalog 附加于非全限定名的表名上。

例如:CATALOG_NAME

hibernate.session_factory_name org.hibernate.SessionFactory 创建后,将自动使用这个名字绑定到 JNDI 中。
hibernate.max_fetch_depth 为单向关联(一对一,多对一)的外连接抓取(outer join fetch)树设置最大深度。值为 0 意味着将关闭默认的外连接抓取。
hibernate.default_batch_fetch_size 为 Hibernate 关联的批量抓取设置默认数量。

例如:建议的取值为 48,和 16

hibernate.default_entity_mode 为由这个 SessionFactory 打开的所有 Session 指定默认的实体表现模式。
hibernate.order_updates 强制 Hibernate 按照被更新数据的主键,为 SQL 更新排序。这么做将减少在高并发系统中事务的死锁。

例如:true | false

hibernate.generate_statistics 如果开启,Hibernate 将收集有助于性能调节的统计数据。

例如:true | false

hibernate.use_identifier_rollback 如果开启,在对象被删除时生成的标识属性将被重设为默认值。

例如:true | false

hibernate.use_sql_comments 如果开启,Hibernate 将在 SQL 中生成有助于调试的注释信息,默认值为 false
hibernate.id.new_generator_mappings Setting is relevant when using @GeneratedValue. It indicates whether or not the new IdentifierGenerator implementations are used for javax.persistence.GenerationType.AUTO, javax.persistence.GenerationType.TABLE and javax.persistence.GenerationType.SEQUENCE. Default to false to keep backward compatibility.

注意

We recommend all new projects which make use of to use @GeneratedValue to also set hibernate.id.new_generator_mappings=true as the new generators are more efficient and closer to the JPA 2 specification semantic. However they are not backward compatible with existing databases (if a sequence or a table is used for id generation).

属性名 用途
hibernate.jdbc.fetch_size 非零值,指定 JDBC 抓取数量的大小(调用 Statement.setFetchSize())。
hibernate.jdbc.batch_size 非零值,允许 Hibernate 使用 JDBC2 的批量更新。

例如:建议取 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.
hibernate.jdbc.factory_class 选择一个自定义的 Batcher。多数应用程序不需要这个配置属性。
hibernate.jdbc.use_scrollable_resultset 允许 Hibernate 使用 JDBC2 的可滚动结果集。只有在使用用户提供的 JDBC 连接时,这个选项才是必要的,否则 Hibernate 会使用连接的元数据。

例如:true | false

hibernate.jdbc.use_streams_for_binary 在 JDBC 读写 binaryserializable 的类型时使用流(stream)(系统级属性)。
hibernate.jdbc.use_get_generated_keys 在数据插入数据库之后,允许使用 JDBC3 PreparedStatement.getGeneratedKeys() 来获取数据库生成的 key(键)。需要 JDBC3+ 驱动和 JRE1.4+,如果你的数据库驱动在使用 Hibernate 的标识生成器时遇到问题,请将此值设为 false。默认情况下将使用连接的元数据来判定驱动的能力。
hibernate.connection.provider_class 自定义 ConnectionProvider 的类名,此类用来向 Hibernate 提供 JDBC 连接。
hibernate.connection.isolation 设置 JDBC 事务隔离级别。查看 java.sql.Connection 来了解各个值的具体意义,但请注意多数数据库都不支持所有的隔离级别。
hibernate.connection.autocommit 允许被缓存的 JDBC 连接开启自动提交(autocommit)(不推荐)。

例如:true | false

hibernate.connection.release_mode 指定 Hibernate 在何时释放 JDBC 连接。默认情况下,直到 Session 被显式关闭或被断开连接时,才会释放 JDBC 连接。对于应用程序服务器的 JTA 数据源,你应当使用 after_statement,这样在每次 JDBC 调用后,都会主动的释放连接。对于非 JTA 的连接,使用 after_transaction 在每个事务结束时释放连接是合理的。auto 将为 JTA 和 CMT 事务策略选择 after_statement,为JDBC事务策略选择 after_transaction
hibernate.connection. <propertyName> 把 JDBC 属性 <propertyName> 传递给 DriverManager.getConnection()
hibernate.jndi. <propertyName> <propertyName> 属性传递给 JNDI InitialContextFactory

属性名 用途
hibernate.cache.provider_class 自定义的 CacheProvider 的类名。
hibernate.cache.use_minimal_puts 以频繁的读操作为代价,优化二级缓存来最小化写操作。在 Hibernate3 中,这个设置对的集群缓存非常有用,对集群缓存的实现而言,默认是开启的。

例如:true | false

hibernate.cache.use_query_cache 允许查询缓存,个别查询仍然需要被设置为可缓存的。

例如:true | false

hibernate.cache.use_second_level_cache 能用来完全禁止使用二级缓存。对那些在类的映射定义中指定 <cache> 的类,会默认开启二级缓存。
hibernate.cache.query_cache_factory 自定义实现 QueryCache 接口的类名,默认为内建的 StandardQueryCache
hibernate.cache.region_prefix 二级缓存区域名的前缀。

例如:prefix

hibernate.cache.use_structured_entries 强制 Hibernate 以更人性化的格式将数据存入二级缓存。

例如:true | false

hibernate.cache.default_cache_concurrency_strategy Setting used to give the name of the default org.hibernate.annotations.CacheConcurrencyStrategy to use when either @Cacheable or @Cache is used. @Cache(strategy="..") is used to override this default.

属性名 用途
hibernate.transaction.factory_class 一个 TransactionFactory 的类名,用于 Hibernate Transaction API(默认为 JDBCTransactionFactory)。
jta.UserTransaction 一个 JNDI 名字,被 JTATransactionFactory 用来从应用服务器获取 JTA UserTransaction
hibernate.transaction.manager_lookup_class 一个 TransactionManagerLookup 的类名 — 当使用 JVM 级缓存,或在 JTA 环境中使用 hilo 生成器的时候需要该类。
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.3 节 “上下文相关的会话(Contextual Session)”.
hibernate.transaction.auto_close_session If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and automatic session context management is preferred, see 第 2.3 节 “上下文相关的会话(Contextual Session)”.

属性名 用途
hibernate.current_session_context_class Supply a custom strategy for the scoping of the "current" Session. See 第 2.3 节 “上下文相关的会话(Contextual Session)” for more information about the built-in strategies.
hibernate.query.factory_class 选择 HQL 解析器的实现。

例如:org.hibernate.hql.ast.ASTQueryTranslatorFactoryorg.hibernate.hql.classic.ClassicQueryTranslatorFactory

hibernate.query.substitutions 将 Hibernate 查询中的符号映射到 SQL 查询中的符号(符号可能是函数名或常量名字)。

例如:hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

hibernate.hbm2ddl.auto SessionFactory 创建时,自动检查数据库结构,或者将数据库 schema 的 DDL 导出到数据库。使用 create-drop 时,在显式关闭 SessionFactory 时,将删除掉数据库 schema。
hibernate.hbm2ddl.import_files

Comma-separated names of the optional files containing SQL DML statements executed during the SessionFactory creation. This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.

hibernate.bytecode.use_reflection_optimizer

Enables the use of bytecode manipulation instead of runtime reflection. This is a System-level property and cannot be set in hibernate.cfg.xml. Reflection can sometimes be useful when troubleshooting. Hibernate always requires either CGLIB or javassist even if you turn off the optimizer.

hibernate.bytecode.provider

Both javassist or cglib can be used as byte manipulation engines; the default is javassist.


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
MySQL5 org.hibernate.dialect.MySQL5Dialect
MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle(any version) org.hibernate.dialect.OracleDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 11g org.hibernate.dialect.Oracle10gDialect
Sybase org.hibernate.dialect.SybaseASE15Dialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
H2 Database org.hibernate.dialect.H2Dialect
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

hibernate.query.substitutions true=1,false=0
hibernate.query.substitutions toLowercase=LOWER
类别 功能
org.hibernate.SQL 在所有 SQL DML 语句被执行时为它们记录日志
org.hibernate.type 为所有 JDBC 参数记录日志
org.hibernate.tool.hbm2ddl 在所有 SQL DDL 语句执行时为它们记录日志
org.hibernate.pretty 在 session 清洗(flush)时,为所有与其关联的实体(最多 20 个)的状态记录日志
org.hibernate.cache 为所有二级缓存的活动记录日志
org.hibernate.transaction 为事务相关的活动记录日志
org.hibernate.jdbc 为所有 JDBC 资源的获取记录日志
org.hibernate.hql.ast.AST 在解析查询的时候,记录 HQL 和 SQL 的 AST 分析日志
org.hibernate.secure 为 JAAS 认证请求做日志
org.hibernate 为任何 Hibernate 相关信息记录日志(信息量较大,但对查错非常有帮助)

SessionFactory sf = new Configuration()

    .setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
    .addFile("Item.hbm.xml")
    .addFile("Bid.hbm.xml")
    .buildSessionFactory();
  • by default, Hibernate uses persisters that make sense in a relational model and follow Java Persistence's specification

  • you can define a PersisterClassProvider implementation that provides the persister class used of a given entity or collection

  • finally, you can override them on a per entity and collection basis in the mapping using @Persister or its XML equivalent

SessionFactory sf = new Configuration()

    .setPersisterClassProvider(customPersisterClassProvider)
    .addAnnotatedClass(Order.class)
    .buildSessionFactory();
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory
        name="java:hibernate/SessionFactory">

        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="org/hibernate/auction/Item.hbm.xml"/>
        <mapping resource="org/hibernate/auction/Bid.hbm.xml"/>

        <!-- cache settings -->
        <class-cache class="org.hibernate.auction.Item" usage="read-write"/>
        <class-cache class="org.hibernate.auction.Bid" usage="read-only"/>
        <collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>

    </session-factory>

</hibernate-configuration>
        
        SessionFactory
        
         sf 
        
        =
        
         
        
        new
        
         
        
        Configuration
        
        ().
        
        configure
        
        ().
        
        buildSessionFactory
        
        ();
      
SessionFactory sf = new Configuration()

    .configure("catdb.cfg.xml")
    .buildSessionFactory();
  • 容器管理的数据源(Container-managed datasources): Hibernate 能使用通过容器管理,并由 JNDI 提供的 JDBC 连接。通常,特别是当处理多个数据源的分布式事务的时候,由一个 JTA 兼容的 TransactionManager 和一个 ResourceManager 来处理事务管理(CMT,容器管理的事务)。当然你可以通过 编程方式来划分事务边界(BMT,Bean 管理的事务)。或者为了代码的可移植性,你也也许会想使用可选的 Hibernate Transaction API。

  • 自动 JNDI 绑定:Hibernate 可以在启动后将 SessionFactory 绑定到 JNDI。

  • JTA Session 绑定: Hibernate Session 可以自动绑定到 JTA 事务作用的范围。只需简单地从 JNDI 查找 SessionFactory 并获得当前的 Session。当 JTA 事务完成时,让 Hibernate来处理 Session 的清洗(flush)与关闭。事务的划分可以是声明式的(CMT),也可以是编程式的(BMT/UserTransaction)。

  • JMX 部署: 如果你使用支持 JMX 应用程序服务器(如,JBoss AS),那么你可以选择将 Hibernate 部署成托管 MBean。这将为你省去一行从Configuration 构建 SessionFactory 的启动代码。容器将启动你的 HibernateService,并完美地处理好服务间的依赖关系(在 Hibernate 启动前,数据源必须是可用的,等等)。

Transaction 工厂类 应用程序服务器
org.hibernate.transaction.JBossTransactionManagerLookup JBoss AS
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
org.hibernate.transaction.JBossTSStandaloneTransactionManagerLookup JBoss TS used standalone (ie. outside JBoss AS and a JNDI environment generally). Known to work for org.jboss.jbossts:jbossjta:4.11.0.Final

<?xml version="1.0"?>
<server>

<mbean code="org.hibernate.jmx.HibernateService"
    name="jboss.jca:service=HibernateFactory,name=HibernateFactory">

    <!-- Required services -->
    <depends>jboss.jca:service=RARDeployer</depends>
    <depends>jboss.jca:service=LocalTxCM,name=HsqlDS</depends>

    <!-- Bind the Hibernate service to JNDI -->
    <attribute name="JndiName">java:/hibernate/SessionFactory</attribute>

    <!-- Datasource settings -->
    <attribute name="Datasource">java:HsqlDS</attribute>
    <attribute name="Dialect">org.hibernate.dialect.HSQLDialect</attribute>

    <!-- Transaction integration -->
    <attribute name="TransactionStrategy">
        org.hibernate.transaction.JTATransactionFactory</attribute>
    <attribute name="TransactionManagerLookupStrategy">
        org.hibernate.transaction.JBossTransactionManagerLookup</attribute>
    <attribute name="FlushBeforeCompletionEnabled">true</attribute>
    <attribute name="AutoCloseSessionEnabled">true</attribute>

    <!-- Fetching options -->
    <attribute name="MaximumFetchDepth">5</attribute>

    <!-- Second-level caching -->
    <attribute name="SecondLevelCacheEnabled">true</attribute>
    <attribute name="CacheProviderClass">org.hibernate.cache.EhCacheProvider</attribute>
    <attribute name="QueryCacheEnabled">true</attribute>

    <!-- Logging -->
    <attribute name="ShowSqlEnabled">true</attribute>

    <!-- Mapping files -->
    <attribute name="MapResources">auction/Item.hbm.xml,auction/Category.hbm.xml</attribute>

</mbean>

</server>