Hibernate学习笔记(二)深入Hibernate的配置文件

来源:互联网 发布:小说 知乎 编辑:程序博客网 时间:2024/06/05 01:26
  • 创建configuration对象
  • hibernate.properties文件与hibernate.cfg.xml文件
  • jdbc连接属性
  • 数据库方言
  • jndi数据源的连接属性
  • hibernate事务属性
  • 二级缓存相关属性
  • 外连接抓取属性
  • 其他常用的配置属性

创建configuration对象:
随着Hibernate所使用配置文件的不同,创建Configuration对象的方式也不相同。通常有如下几种配置Hibernate的方式:
1、使用hibernate.properties作为配置文件
hibernate.proerties适合初学者,因为很多Hibernate配置文件的详细格式和需要哪些属性。只需要将project\etc路径下的hibernate.properties文件打开需要的注释就可以使用。但是在创建Configruation对象时,需要手动的添加映射文件,代码中手动添加映射文件,远不如将映射文件卸载hibernate.hbm.xml文件中,所以实际开发中一般使用hibernate.hbm.xml,而不使用hibernate.properties
Configuration conf = new Configuration().addResource("Item.hbm.xml").addResource("Bid.hbm.xml");
由于持久化类和映射文件是一一对应的,所以也可以采用向Configuration对象添加持久化类,让Hibernate自己搜索映射文件,如下
Configuration conf = new Configuration().addClass(lee.Item.class).addClass(lee.Bid.class);
这种方式的作用需要注意的是映射文件应该和持久化类放在相同的包路径下,且文件名必须为类名加上.hbm.xml。否则会报org.hibernate.MappingNotFoundException这个错误。

Configuration conf = new Configuration().addResource("org/crazyit/app/domain/News.hbm.xml");映射文件名和路径可以任意
Configuration conf = new Configuration().addClass(org.crazyit.app.domain.News.class);映射文件名和路径必须在PO类的包路径下。
/myhibernate_002/src/hibernate.properties:
## MySQLhibernate.dialect org.hibernate.dialect.MySQLInnoDBDialecthibernate.connection.driver_class com.mysql.jdbc.Driverhibernate.connection.url jdbc:mysql://localhost:3306/hibernatehibernate.connection.username roothibernate.connection.password phpwind.net#################################### Hibernate Connection Pool ####################################hibernate.connection.pool_size 1############################## C3P0 Connection Pool##############################hibernate.c3p0.max_size 20hibernate.c3p0.min_size 1hibernate.c3p0.timeout 5000hibernate.c3p0.max_statements 100hibernate.c3p0.idle_test_period 3000hibernate.c3p0.acquire_increment 2hibernate.c3p0.validate true################################# Miscellaneous Settings ################################### print all generated SQL to the consolehibernate.show_sql true## format SQL in log and consolehibernate.format_sql true## add comments to the generated SQLhibernate.use_sql_comments true#hibernate.hbm2ddl.auto create-drop#hibernate.hbm2ddl.auto createhibernate.hbm2ddl.auto update#hibernate.hbm2ddl.auto validate

2、使用hibernate.cfg.xml作为配置文件
Configuration conf = new Configuration().configure();
映射文件已经添加在了hibernate.cfg.xml中,所以不需要在通过编程方式添加配置文件。
/myhibernate_002/src/hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>        <property name="connection.username">root</property>        <property name="connection.password">phpwind.net</property>       <property name="hibernate.c3p0.max_size">20</property><property name="hibernate.c3p0.min_size">1</property><property name="hibernate.c3p0.timeout">5000</property><property name="hibernate.c3p0.max_statements">100</property><property name="hibernate.c3p0.idle_test_period">3000</property><property name="hibernate.c3p0.acquire_increment">2</property>        <property name="hibernate.c3p0.validate">true</property>                <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>        <property name="show_sql">true</property>        <property name="format_sql">false</property>        <property name="hbm2ddl.auto">update</property>        <property name="use_sql_comments">true</property>        <mapping resource="org/crazyit/app/domain/News.hbm.xml"/>    </session-factory></hibernate-configuration>

3、不使用配置文件创建Configuration实例
这种方法一般不用,太繁琐了,hibernate相关属性和代码耦合度太高,不过可以结合以上两种方式,将部分属性的配置放在代码中。
通过Configuration对象提供的下列三个方法:
Configuration addResource(String resourceName):用于为Configuration对象添加一个映射文件。
Configuration setProperties(Porperties properties):用于为Configuration对象设置一系列属性,这些属性通过Properties实例传入。
Configuration setProperty(String propertyName,String value):为Configuration对象设置一个单独属性。
如:conf = new Configuration().addClass(lee.Item.class).setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")....;
package lee;import org.crazyit.app.domain.News;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class NewsManagerTest2 {public static void main(String[] args) {Configuration conf = new Configuration().addResource("org/crazyit/app/domain/News.hbm.xml").setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver").setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate").setProperty("hibernate.connection.username", "root").setProperty("hibernate.connection.password", "phpwind.net").setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");SessionFactory sf = conf.buildSessionFactory();Session sess = sf.openSession();Transaction tx = sess.beginTransaction();News n = new News();n.setTitle("title");n.setContent("context");sess.save(n);tx.commit();sess.close();sf.close();}}

hibernate.properties文件与hibernate.cfg.xml文件:
使用hibernate.properties文件作为配置文件,使用简单,适用于初学者,只需要在project\etc路径下的拷贝hibernate.properties文件,稍作修改即可,从文件中可以看到配置文件使用的是典型的Properties文件的格式。
hibernate.cfg.xml文件通过<session-factory>标签下的<property >标签,不同的name属性,赋予不同的文本值来达到配置hibernate的目的。还需要在<session-factory>标签中添加<mapping resource="x/xx/abc.hbm.xml" />来指定映射文件。
使用两种方式都可以完成hibernate开发,项目开发中多是使用hibernate.cfg.xml,真正项目中一般都是整合Spring框架,数据库连接池的配置和映射文件的添加都写在applicationContext.xml文件中。

jdbc连接属性:
属性解释:
hibernate.connection.driver_class com.mysql.jdbc.Driver 设置数据库连接驱动
hibernate.connection.url jdbc:mysql:///test 设置连接数据库服务的URL
hibernate.connection.username gavin 连接数据库的用户名
hibernate.connection.password 连接数据库的密码
hibernate.connection.pool_size 1 设置Hibernate数据库连接池的最大并发连接数
hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect  设置连接数据库所使用的方言
上面配置了Hibernate数据库连接池的最大并发数,但Hibernate自带的连接池仅有测试价值,不推荐实际项目中使用。实际项目中可以使用C3P0或者Proxool连接池。使用C3P0或者Proxool需要用下列属性代替hibernate.connection.pool_size属性值。
hibernate.c3p0.max_size 2   C3P0连接池最大连接数
hibernate.c3p0.min_size 2    C3P0连接池最小连接数
hibernate.c3p0.timeout 5000  C3P0连接池中连接的超时时长
hibernate.c3p0.max_statements 100  C3P0缓存Statement的数量
下了三个属性可以用,也可以不用。
hibernate.c3p0.idle_test_period 3000  每隔3000秒检查连接池里的空闲连接 ,单位是秒内的所有链接对象是否超时 
hibernate.c3p0.acquire_increment 2  当连接池里面的连接用完的时候,C3P0一下获取的新的连接数
hibernate.c3p0.validate false  每次都验证连接是否可用

hibernate中配置下列属性实例:
############################## C3P0 Connection Pool###############################hibernate.c3p0.max_size 2#hibernate.c3p0.min_size 2#hibernate.c3p0.timeout 5000#hibernate.c3p0.max_statements 100#hibernate.c3p0.idle_test_period 3000#hibernate.c3p0.acquire_increment 2#hibernate.c3p0.validate false

使用XML配置文件:
<!-- 最大连接数 --><property name="hibernate.c3p0.max_size">20</property><!-- 最小连接数 --><property name="hibernate.c3p0.min_size">5</property><!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 --><property name="hibernate.c3p0.timeout">120</property><!-- 最大的PreparedStatement的数量 --><property name="hibernate.c3p0.max_statements">100</property><!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒--><property name="hibernate.c3p0.idle_test_period">120</property><!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 --><property name="hibernate.c3p0.acquire_increment">2</property><!-- 每次都验证连接是否可用 --><property name="hibernate.c3p0.validate">true</property>

数据库方言:
由于hibernate支持各种数据库,而每种数据库都对标准sql进行一些扩展,语法细节上存着差异(如mysql使用limit进行分页查询,而标准的sql不支持limit关键字,oracle则需要使用行内试图的方式进行分页),所以需要根据使用数据库的不同,配置不同的方言。
注意:不管是Hibernate自己管理数据源,还是直接访问容器管理的数据库,都需要指定数据库方言。



jndi数据源的连接属性:
Hibernate可以使用JNDI(Java Naming Directory Interface,Java命名目录接口)数据源的相关配置,下面是连接JNDI数据源的主要配置属性:
hibernate.connection.datasource: 指定数据源JNDI名字。
hibernate.jndi.url:  指定JNDI提供者的URL,该属性是可选的。如果JNDI与Hibernate持久化访问的代码处于同一个应用中,则无须指定该属性。
hibernate.jndi.class: 指定JNDI InitialContextFactory的实现类,该属性也是可选的。如果JNDI与Hibernate持久化访问的代码处于同一个应用中,则无须指定该属性。
hibernate.connection.username: 指定连接数据库的用户名,该属性是可选的。
hibernate.connection.password: 指定连接数据库的密码,该属性是可选的。

属性的配置文件中使用:
## JNDI Datasource
#hibernate.connection.datasource jdbc/test
#hibernate.connection.username db2
#hibernate.connection.password db2
配置Hibernate连接Tomcat中数据源的配置:
<!-- 配置JNDI数据源的JNDI名 -->
<property name="connection.datasource">java:comp/env/jdbc/dstest</property>
<!-- 配置数据库的方言 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
如果数据源所在容器支持跨事务资源的全局事务管理,从JNDI数据源获得的JDBC连接,可自动参与容器管理的全局事务,而不仅仅是Hibernate的局部事务。

hibernate事务属性:
Hibernate不仅提供了局部事务支持,也允许使用容器管理的全局事务。Hibernate关于事务管理的属性:
hibernate.transaction.factory_class:指定Hibernate所用的事务工厂的类型,该属性必须是TransactionFactory的直接或者间接子类。
jta.UserTransaction:该属性是一个JNDI名,Hibernate将使用JTATransactionFactory从应用服务器获取JTA UserTransaction。
hibernate.transaction.manager_lookup_class:该属性值应为一个TransactionManagerLookup类名,当使用JVM级别的缓存时,或在JTA环境中使用hilo生成器策略时,需要该类。
hibernate.transaction.flush_before_completion:指定Session是否在事务完成后自动将数据刷新(flush)到底层数据库,属性值只能为true或false。现在更好的方法时使用Context相关的Session管理。
hibernate.transaction.auto_close_session:指定是否在事务结束后自动关闭Session,该属性值只能为true或false。现在更好的方法时使用Context相关的Session管理。
摘自hibernate-release-4.3.8.Final\project\etc\hibernate.properties:
########################## Transaction API ############################ the Transaction API abstracts application code from the underlying JTA or JDBC transactions#hibernate.transaction.factory_class org.hibernate.transaction.JTATransactionFactory#hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory## to use JTATransactionFactory, Hibernate must be able to locate the UserTransaction in JNDI## default is java:comp/UserTransaction## you do NOT need this setting if you specify hibernate.transaction.manager_lookup_class#jta.UserTransaction jta/usertransaction#jta.UserTransaction javax.transaction.UserTransaction#jta.UserTransaction UserTransaction## to use the second-level cache with JTA, Hibernate must be able to obtain the JTA TransactionManager#Hibernate使用JTA的第二级缓存,必须能够获得JTA TransactionManager#hibernate.transaction.manager_lookup_class org.hibernate.transaction.JBossTransactionManagerLookup#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WeblogicTransactionManagerLookup#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WebSphereTransactionManagerLookup#hibernate.transaction.manager_lookup_class org.hibernate.transaction.OrionTransactionManagerLookup#hibernate.transaction.manager_lookup_class org.hibernate.transaction.ResinTransactionManagerLookup## Enable automatic flush during the JTA beforeCompletion() callback## (This setting is relevant with or without the Transaction API)#hibernate.transaction.flush_before_completion## Enable automatic session close at the end of transaction## (This setting is relevant with or without the Transaction API)#hibernate.transaction.auto_close_session

二级缓存相关属性:
Hibernate的SessionFactory可持有一个可选的二级缓存,通过使用这种二级缓存可以提高Hibernate的持久化访问的性能。Hibernate有关于二级缓存的如下属性:
hibernate.cache.provider_class:该属性用于设置二级缓存CacheProvider的类名。
hibernate.cache.use_minimal_puts:以频繁的读写作为代价,优化二级缓存以实现最小化写操作。在Hibernate 3中,这个设置对集群缓存非常有用,对集群缓存实现而言,默认是开启的。
hibernate.cache.use_query_cache:设置是否允许查询缓存。个别查询仍然需要显示设置为可缓存的。
hibernate.cache.use_second_level_cache:设置是否启用二级缓存。
hibernate.cache.query_cache_factory:设置查询缓存工厂的类名,查询缓存工厂必须实现QueryCache接口。该属性值默认为内建的StandardQueryCache。
hibernate.cache.region_prefix:设置二级缓存区名称的前缀。
hibernate.cache.use_structured_entries:用于设置是否强制Hibernate以可读性更好的格式将数据存入二级缓存。
摘自hibernate-release-4.3.8.Final\project\etc\hibernate.properties:
############################# Second-level Cache ############################### optimize cache for minimal "puts" instead of minimal "gets" (good for clustered cache)#hibernate.cache.use_minimal_puts true## set a prefix for cache region nameshibernate.cache.region_prefix hibernate.test## disable the second-level cache#hibernate.cache.use_second_level_cache false## enable the query cache#hibernate.cache.use_query_cache true## store the second-level cache entries in a more human-friendly format#hibernate.cache.use_structured_entries true## choose a cache implementation#hibernate.cache.region.factory_class org.hibernate.cache.infinispan.InfinispanRegionFactory#hibernate.cache.region.factory_class org.hibernate.cache.infinispan.JndiInfinispanRegionFactory#hibernate.cache.region.factory_class org.hibernate.cache.internal.EhCacheRegionFactory#hibernate.cache.region.factory_class org.hibernate.cache.internal.SingletonEhCacheRegionFactoryhibernate.cache.region.factory_class org.hibernate.cache.internal.NoCachingRegionFactory## choose a custom query cache implementation#hibernate.cache.query_cache_factory

外连接抓取属性:
外连接抓取能限制执行SQL语句的次数来提高效率,这种外连接抓取通过单个select语句中使用outer join来一次抓取多个数据表的数据。外连接抓取允许在单个select语句中,通过<many-to-one../>、<one-to-many../>、<many-to-many../>和<one-to-one../>等关联获取连接对象的整个对象图。
将hibernate.max_fetch_depth设为0,将在全局范围内禁止外连接抓取,设为1或更高值能启用N-1或1-1的外连接抓取。除此之外,还应该在映射文件中通过fetch="join"来指定这种外连接抓取。
## set the maximum depth of the outer join fetch tree
hibernate.max_fetch_depth 1

其他常用的配置属性:
hibernate.show_sql  :是否在控制台输出hibernate生成的sql语句,只能为true或false。
hibernate.format_sql:是否将SQL语句转化为格式良好的SQL语句。只接受true和false两个值。
hibernate.use_sql_comments:是否在Hibernate生成的SQL语句中添加有助于调试的注释。
hibernate.jdbc.fetch_size:指定JDBC抓取数量的大小,它可接受一个整数值,其实质是调用Statement.setFetchSize()方法。
hibernate.jdbc.batch_size:指定Hibernate使用JDBC的批量更新的大小,它可以接受一个整数值,建议取5到31之间的值。
hibernate.connection.autocommit:设置是否自动提交,通常不建议打开自动提交。
hibernate.hbm2ddl.auto:设置当创建SessionFactory时,是否根据映射文件自动创建数据库表。如果使用的是create-drop值,显示关闭SessionFactory时,将Drop刚建的数据库表。create表示每次都会删除表(表存在的话),建表,插入语句。update表示表不存在的话,建表再插入语句,表存着的话直接插入语句。validate表示先验证表是否存着,存着则插入数据,不存在则不进行任何操作。
摘自hibernate-release-4.3.8.Final\project\etc\hibernate.properties:
################################# Miscellaneous Settings ################################### print all generated SQL to the console#hibernate.show_sql true## format SQL in log and consolehibernate.format_sql true## add comments to the generated SQL#hibernate.use_sql_comments true## generate statistics#hibernate.generate_statistics true## auto schema export#hibernate.hbm2ddl.auto create-drop#hibernate.hbm2ddl.auto create#hibernate.hbm2ddl.auto update#hibernate.hbm2ddl.auto validate## specify a default schema and catalog for unqualified tablenames#hibernate.default_schema test#hibernate.default_catalog test## enable ordering of SQL UPDATEs by primary key#hibernate.order_updates true## set the maximum depth of the outer join fetch treehibernate.max_fetch_depth 1## set the default batch size for batch fetching#hibernate.default_batch_fetch_size 8## rollback generated identifier values of deleted entities to default values#hibernate.use_identifer_rollback true## enable bytecode reflection optimizer (disabled by default)#hibernate.bytecode.use_reflection_optimizer true


0 0
原创粉丝点击