---
title: "Hibernate Core Reference Manual学习笔记——Chapter 3. Configuration"
author: "SOLO__Player"
date: "2013-01-01T15:34:13Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-core-reference-manual-chapter-3-configuration"
draft: false
lastmod: "2013-01-01T15:34:13Z"
id: 1758111
url: "https://soloplayer.iteye.com/blog/1758111"
---

[Hibernate Core Reference Manual](http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/ "Hibernate Core Reference Manual")

 

Chapter 3. Configuration

Table of Contents

3.1. Programmatic configuration  
3.2. Obtaining a SessionFactory  
3.3. JDBC connections  
3.4. Optional configuration properties  
3.4.1. SQL Dialects  
3.4.2. Outer Join Fetching  
3.4.3. Binary Streams  
3.4.4. Second-level and query cache  
3.4.5. Query Language Substitution  
3.4.6. Hibernate statistics  
3.5. Logging  
3.6. Implementing a NamingStrategy  
3.7. Implementing a PersisterClassProvider  
3.8. XML configuration file  
3.9. Java EE Application Server integration  
3.9.1. Transaction strategy configuration  
3.9.2. JNDI-bound SessionFactory  
3.9.3. Current Session context management with JTA  
3.9.4. JMX deployment

Hibernate被设计成可以在很多种不同的环境下运行，所以它有很多的配置参数。幸运的是，大多数参数都有合理的默认值，并且在Hibernate的发行包中 etc/目录下有个hibernate.properties示例文件。你只需将其拷贝到你的classpath，并自定义其中的参数来适合你的需求。

3.1. Programmatic configuration  
一个org.hibernate.cfg.Configuration的类实例代表从应用程序的java类型到数据库SQL类型映射的整个集合。org.hibernate.cfg.Configuration被用来构建不可变的org.hibernate.SessionFactory。映射关系会从所有的映射文件编译而来。  
你可以通过直接指定映射文件来获得org.hibernate.cfg.Configuration 的实例。如果映射文件在classpath下，使用addResource()，如下：

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

   
另一种方式是指定被映射的类，让Hibernate来为你找到映射文件：

```
Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class);
```

   
接下来Hibernate就会在classpath下寻找 /org/hibernate/auction/Item.hbm.xml 和 /org/hibernate/auction/Bid.hbm.xml这两个文件。这种方式消除了硬编码文件名。  
org.hibernate.cfg.Configuration同样允许你指定配置参数。如下：

```
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");
```

 

   
这并不是向Hibernate传递配置参数的唯一方式，你还可以采用下面的方法：  
1.传递一个java.util.Properties 类实例给Configuration.setProperties()方法。  
2.在classpath的根目录放置一个名为 hibernate.properties的文件。  
3.通过使用java -Dproperty=value.设置系统参数。  
4.在 hibernate.cfg.xml文件中包含&lt;property&gt;标签（后面会讨论）

如果你想以最快的速度开始，hibernate.properties 是最简单的方式。 org.hibernate.cfg.Configuration被视为启动期对象，一旦SessionFactory 创建完成，org.hibernate.cfg.Configuration实例就会被抛弃。

3.2. Obtaining a SessionFactory  
当所有的映射关系被org.hibernate.cfg.Configuration解析之后，应用程序必须获得一个创建org.hibernate.Session类实例的工厂。这个工厂通常被应用程序的所有线程所共享。

```
SessionFactory sessions = cfg.buildSessionFactory();
```

   
Hibernate只允许你的应用程序实例化一个 org.hibernate.SessionFactory.如果你使用多个数据库，这将会很有用。

3.3. JDBC connections

建议让org.hibernate.SessionFactory 来为你创建和管理（pool）JDBC连接。如果你采用这种方式，打开一个org.hibernate.Session就像下面这样简单：

```
Session session = sessions.openSession(); // open a new Session
```

 

   
一旦你开始了一项需要访问数据库的任务，你就会从连接池中获得一个JDBC连接。  
在你可以做这个之前，你需要传递一些JDBC连接参数到Hibernate。所有的Hibernate属性名称和语义都定义在org.hibernate.cfg.Environment类中。JDBC连接最重要的参数如下表所列：  
如果你设置了下面的参数，Hibernate会使用java.sql.DriverManager 来获得和管理（pool）数据库连接。

[]()

**Table 3.1. Hibernate JDBC Properties**

 

 

  [Property name Purpose hibernate.connection.driver\_class *JDBC driver class* hibernate.connection.url *JDBC URL* hibernate.connection.username *database user* hibernate.connection.password *database user password* hibernate.connection.pool\_size *maximum number of pooled connections*]()

[]()

Hibernate本身的连接池算法非常的初级。是为了帮助你快速开始，而不是为了用于生产环境，甚至是性能测试。为了最好的性能和稳定性，你应该使用第三方连接池。只需用指定其它连接池的参数替换hibernate.connection.pool\_size参数。这样就关闭了Hibernate自身的连接池。比如：你可能喜欢使用c3p0。

C3P0是一个开源的JDBC连接池，在Hibernate发行版的lib目录下你可以找到它。如果你设置了hibernate.c3p0.\*参数，Hibernate将会使用org.hibernate.connection.C3P0ConnectionProvider进行连接池工作。  
如果你喜欢使用Proxool，更多信息请参考打包的hibernate.properties文件和Hibernate网站。设置了c3p0的 hibernate.properties 样例文件如下：

 

```
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
```

   
[]()

For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server `javax.sql.Datasource` registered in JNDI. You will need to set at least one of the following properties:（以后看）

 

[]()[]()

**Table 3.2. Hibernate Datasource Properties**

 

 

  [Property name Purpose hibernate.connection.datasource *datasource JNDI name* hibernate.jndi.url *URL of the JNDI provider* (optional) hibernate.jndi.class *class of the JNDI `InitialContextFactory`*  (optional) hibernate.connection.username *database user* (optional) hibernate.connection.password *database user password* (optional)]()

[]()

 

[]()

Here is an example `hibernate.properties` file for an application server provided JNDI datasource:

```
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.PostgreSQL82Dialect
```

[]()[]()  

JDBC connections obtained from a JNDI datasource will automatically participate in the container-managed transactions of the application server.

 

Arbitrary connection properties can be given by prepending "hibernate.connection" to the connection property name. For example, you can specify a charSet connection property using hibernate.connection.charSet.

 

You can define your own plugin strategy for obtaining JDBC connections by implementing the interface org.hibernate.connection.ConnectionProvider, and specifying your custom implementation via the hibernate.connection.provider\_class property.

 

3.4. Optional configuration properties

还有很多的参数用来控制Hibernate运行时的行为。不过，它们都是可选的，并且都有合理的默认值。

注意：一些属性是"system-level"，系统级别的属性只能通过java -Dproperty=value 或者hibernate.properties这两种方式进行设置。

[]()

**Table 3.3. Hibernate Configuration Properties**

[]()

注意：我们建议所有使用@GeneratedValue的新项目，也要设置hibernate.id.new\_generator\_mappings=true。这样新的生成器会更加高效而且更加接近JPA2的语法规范。但是这样的设置并不向后兼容已存在的数据库（如果它使用序列或表来进行ID生成）

**Table 3.4. Hibernate JDBC and Connection Properties**

**Table 3.5. Hibernate Cache Properties**

**Table 3.6. Hibernate Transaction Properties**

**Table 3.7. Miscellaneous Properties**

 

 

3.4.1. SQL Dialects

总要给hibernate.dialect属性设置正确的值，也就是对应你数据库的org.hibernate.dialect.Dialect类的子类。如果你指定一种方言，Hibernate将会给上面列出来的的属性设置合理的默认值，免去你手动设置。

Table 3.8. Hibernate SQL Dialects (hibernate.dialect)

 

3.4.2. Outer Join Fetching

如果你的数据库支持ANSI, Oracle 或者Sybase形式的外连接，outer join fetching通常可以通过减少与数据库交换数据次数来提高性能。但是，这可能会增大数据库本身的压力。outer join fetching允许在一个SQL SELECT查询中检索出通过many-to-one, one-to-many, many-to-many 和one-to-one关联到一起的整个对象图。

通过设置属性hibernate.max\_fetch\_depth的值为0，可以在全局禁用Outer join fetching。把值设为1或者更大将对映射为fetch="join"的one-to-one 和 many-to-one关联启用Outer join fetching。

See Section 20.1, “Fetching strategies” for more information.

 

3.4.3. Binary Streams

Oracle限制从它的JDBC驱动输入和输出的byte数组的大小。如果你想要使用binary类型和serializable类型的大体积实例，你应该启用hibernate.jdbc.use\_streams\_for\_binary。这是一个system-level属性。

 

3.4.4. Second-level and query cache

 

See the Section 20.2, “The Second Level Cache” for more information.

 

3.4.5. Query Language Substitution

 

3.4.6. Hibernate statistics

 

3.5. Logging

3.6. Implementing a NamingStrategy

3.7. Implementing a PersisterClassProvider（以后看）

3.8. XML configuration file

另一种配置Hibernate的方式是创建一个名为hibernate.cfg.xml的文件。hibernate.cfg.xml被用来替代hibernate.properties，如果两个文件都创建了，hibernate.cfg.xml会覆盖hibernate.properties的配置。hibernate.cfg.xml应该放在CLASSPATH根目录。下面是文件示例：

 

```
<?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>
```

  这种方式的优点是the externalization of the mapping file names to configuration。一旦你不得不调整Hibernate cache,使用hibernate.cfg.xml 文件会很方便。你可以选择使用hibernate.properties 或者 hibernate.cfg.xml，除了上面提到的XML配置文件的优点，二者是等价的。使用XML配置文件，使用Hibernate就像下面这样简单：

 

```
SessionFactory sf = new Configuration().configure().buildSessionFactory();
```

 或者你可以使用一个不同的XML配置文件:

 

```
SessionFactory sf = new Configuration()
    .configure("catdb.cfg.xml")
    .buildSessionFactory();
```

 

3.9. Java EE Application Server integration（以后看）