Hibernate参考手册学习与实践:配置

来源:互联网 发布:javascript对象转json 编辑:程序博客网 时间:2024/05/17 21:44

Hibernate 配置

前言:使用Hibernate也有一段时间了,但总没时间好好看看它的细节。现在每天利用一点时间把Hibernate参考手册再好好学习一下,并摘要部分认为比较重要的内容。现在Hibernate已经有大把的资料,翻译参考手册并无太大的价值,本文纯粹是为了加深对Hibernate的理解而已,是写给自己看。

第三章 配置

Hibernate是为在不同的环境中使用而设计,正因如此它有大量的配置参数。幸运的是,它们中的大多数都有明显的默认值,而且Hibernate在发布时使用了示例文件 hibernate.properties(在/etc下)来说明不同的选项。只需要简单的将示例文件放到你的classpath下,然后根据你的需要修改它。

3.1 程序化配置

一个 org.hibernate.cfg.Configuration的实例展示了Java类型到SQL数据库的全部的映射。 org.hibernate.cfg.Configuration类是用于创建不可变的org.hibernate.SessionFactory的。这些映射是由一系列的XML映射文件编译而来。
你可以使用指定XML映射文件的方式直接实例化 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. 将名为hibernate.properties的文件放在classpath的根目录下。
3. 使用java -Dproperty=value设置System属性。
4. 在 hibernate.cfg.xml内包含<property>元素。(会在后面讨论)

如果你想快速启动,hibernate.properties是最容易的路径。
org.hibernate.cfg.Configuration是作为启动时的对象,一旦SessionFactory被创建,它将被丢弃。

3.2 获得SessionFactory

当所有的映射都被org.hibernate.cfg.Configuration解析后,应用程序必须获得org.hibernate.Sessions实例的工厂。此工厂将被所有的应用程序共享:

SessionFactory sessions = cfg.buildSessionFactory();

Hibernate允许你的应用程序实例化多个org.hibernate.SessionFactory。如果你使用多个数据库,这比较有用。

3.3 JDBC连接

建议使用org.hibernate.SessionFactory创建并池化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获取并池化数据库连接。
表3.1 Hibernate JDBC属性

属性名 目的 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的web站点以获取跟多的信息。
下面是c3p0的配置在hibernate.properties文件中的示例:

hibernate.connection.driver_class = org.postgresql.Driverhibernate.connection.url = jdbc:postgresql://localhost/mydatabasehibernate.connection.username = myuserhibernate.connection.password = secrethibernate.c3p0.min_size=5hibernate.c3p0.max_size=20hibernate.c3p0.timeout=1800hibernate.c3p0.max_statements=50hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

在应用服务器中使用时,你应该几乎总是将Hibernate配置为从注册在JNDI中的应用服务器的javax.sql.Datasource来获取连接。你应该至少设置以下的一个属性:
表3.2 Hibernate Datasource属性

属性名 目的 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)

下面是提供了JNDI数据源应用服务器的示例hibernate.properties文件:

hibernate.connection.datasource = java:/comp/env/jdbc/testhibernate.transaction.factory_class = \    org.hibernate.transaction.JTATransactionFactoryhibernate.transaction.manager_lookup_class = \    org.hibernate.transaction.JBossTransactionManagerLookuphibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect

从JNDI数据源获得的数据库连接将自动参与应用服务器的容器管理的事务。
可以在连接属性名前加上前缀”hibernate.connection”而构成任意想要的连接属性。比如,你可以使用hibernate.connection.charSet来指定一个charSet的连接属性。
你可以通过实现org.hibernate.connection.ConnectionProvider接口来定义你自己的获取JDBC连接的插件策略,并且可以通过hibernate.connection.provider_class 类的属性指定你自己的实现。

3.4. 可选配置属性

还有其他很多属性控制运行时Hibernate行为的属性。所有这些可选属性都有合理的默认值。
警告:这里的很多属性只是“系统”级。系统级的属性只能通过java -Dproperty=value或者在hibernate.properties中设置。它们不能被上述的其他技术设置。
Table 3.3. Hibernate Configuration Properties

Property name Purpose hibernate.dialect The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database. e.g. full.classname.of.Dialect .In most cases Hibernate will actually be able to choose the correct org.hibernate.dialect.Dialect implementation 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. e.g. true | false hibernate.format_sql Pretty print the SQL in the log and console. e.g. true | false hibernate.default_schema Qualify unqualified table names with the given schema/tablespace in generated SQL. e.g. SCHEMA_NAME hibernate.default_catalog Qualifies unqualified table names with the given catalog in generated SQL. e.g. CATALOG_NAME hibernate.session_factory_name The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created. e.g. jndi/composite/name hibernate.max_fetch_depth Sets 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. e.g. recommended values between 0 and 3 hibernate.default_batch_fetch_size Sets a default size for Hibernate batch fetching of associations. e.g. recommended values 4, 8, 16 hibernate.default_entity_mode Sets a default mode for entity representation for all sessions opened from this SessionFactory, defaults to pojo.e.g. dynamic-map | pojo hibernate.order_updates Forces 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. e.g. true | false hibernate.generate_statistics If enabled, Hibernate will collect statistics useful for performance tuning. e.g. true | false hibernate.use_identifier_rollback If enabled, generated identifier properties will be reset to default values when objects are deleted. e.g. true | false hibernate.use_sql_comments If turned on, Hibernate will generate comments inside the SQL, for easier debugging, defaults to false. e.g. true| 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. e.g. true | false

Note
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).

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类的子类。如果你指定了一个dialect,Hibernate将会对上述的其他属性使用明显的默认值。这意味着你不必手动设置它们。
Table 3.8. Hibernate SQL Dialects (hibernate.dialect)

RDBMS Dialect Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect Microsoft SQL Server 2012 org.hibernate.dialect.SQLServer2012Dialect MySQL org.hibernate.dialect.MySQLDialect MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect MySQL5 org.hibernate.dialect.MySQL5Dialect MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect Oracle 8i org.hibernate.dialect.Oracle8iDialect Oracle 9i org.hibernate.dialect.Oracle9iDialect Oracle 10g and later org.hibernate.dialect.Oracle10gDialect Oracle TimesTen org.hibernate.dialect.TimesTenDialect PostgreSQL 8.1 org.hibernate.dialect.PostgreSQL81Dialect PostgreSQL 8.2 org.hibernate.dialect.PostgreSQL82Dialect PostgreSQL 9 and later org.hibernate.dialect.PostgreSQL9Dialect 其他 略

3.4.2 外连接抓取

对于支持外连接的数据库,外连接抓取数据可以提高性能。通过 hibernate.max_fetch_depth属性为0是关闭外连接,1即以上打开以实现one-to-one和many-to-one关联的外连接抓取。
参考20.1节的“抓取策略”

3.4.3 二进制流(略)

3.4.4 二级缓存

带前缀hibernate.cache的属性设置Hibernate的二级缓存。参考20.2节的“二级缓存”。

3.4.5 查询语言替换(略)

3.4.6 Hibernate统计(略)

3.5 日志(略)

3.6 实现NamingStrategy(略)

3.7 实现PersisterClassProvider(略)

3.8 XML配置文件

另一种配置方法是在名为 hibernate.cfg.xml的文件中指定全部的配置。这个文件可以用来替换hibernate.properties文件,如果这两个文件都存在,将会覆盖属性文件。
这个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>

此方法的优点是将映射文件名的位置外化。hibernate.cfg.xml文件在微调Hibernate缓存是也更加方便。 hibernate.cfg.xml除了在XML语法上好处外,它和是等同的,使用哪一个取决于用户。
使用XML配置文件,启动Hibernate可以简化如下:

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

你也可以选择一个不同配置文件,如:

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

3.9 Java EE应用服务器集成(略)

0 0
原创粉丝点击