Hibernate 总结2:配置方法

关于Struts2 + spring + hibernate进Q群: 130529143交流。
有偿技术支持Q群:
398162181 


注意:数据库基本配置信息(如数据库方言)参考:

hibernate-release-5.0.1.Final\project\etc\hibernate.properties  ;


1.加入相应的 *.jar包:

1.1 官方下载:hibernate-release-5.0.1.Final.zip,解压后得到:hibernate-release-5.0.1.Final 文件夹。

    hibernate-release-5.0.1.Final\lib\required\ 路径下所有jar包;

1.2 不同数据库连接所需的jdbc     *.jar包:

mysql:   mysql-connector-java-5.1.25-bin.jar   ;

oracle:  ojdbc14.jar ;

sqlserver:sqljdbc4.jar;

1.3 加入到lib下,并add to build path ;



2.配置hibernate.cfg.xml文件:

2.1 在类路径下新建  hibernate.cfg.xml文件:


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


   
root
root
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/hibernate5




org.hibernate.dialect.MySQLInnoDBDialect

true

true


update

2

true



20
5
2
2000
50000
10


100

30








3.生成实体类相应的 *.hbm.xml文件:


"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

   
       
           
           
       

       
           
       

       
       
           
               
           

           
           
       

   



4.将 *.hbm.xml文件引入到hibernate.cfg.xml文件中:

将3.中的  *.hbm.xml 加入 2.种的hibernate.cfg.xml。



5.配置c3p0数据源:

5.1 官方下载:hibernate-release-5.0.1.Final.zip,解压后得到:hibernate-release-5.0.1.Final 文件夹。

将hibernate-release-5.0.1.Final\lib\optional\c3p0路径下所有jar包添加到类路径下;

  5.2 在hibernate.cfg.xml文件中配置c3p0数据源 如 2 所示:

ibernate.c3p0.max_size: 数据库连接池的最大连接数
hibernate.c3p0.min_size: 数据库连接池的最小连接数
hibernate.c3p0.acquire_increment: 当数据库连接池中的连接耗尽时, 同一时刻获取多少个数据库连接
hibernate.c3p0.timeout:   数据库连接池中连接对象在多长时间没有使用过后,就应该被销毁
hibernate.c3p0.idle_test_period:  表示连接池检测线程多长时间检测一次池内的所有链接对象是否超时. 
连接池本身不会把自己从连接池中移除,而是专门有一个线程按照一定的时间间隔来做这件事,
这个线程通过比较连接对象最后一次被使用时间和当前时间的时间差来和 timeout 做对比,进而决定是否销毁这个连接对象。 
hibernate.c3p0.max_statements:  缓存 Statement 对象的数量



6.hibernate缓存:

6.1 一级缓存:在Session中;

hibernate-release-5.0.1.Final.zip,解压后得到:hibernate-release-5.0.1.Final 文件夹。

   hibernate-release-5.0.1.Final\lib\optional\c3p0路径下所有jar包;

   6.2  二级缓存:在SessionFactory中;

1). 加入二级缓存插件的 jar 包及配置文件:

I. 复制   hibernate-release-5.0.1.Final\lib\optional\ehcache*.jar   到当前 应用的类路径下.
II. 复制  hibernate-release-5.0.1.Final\project\etc\ehcachexml       到当前 WEB 应用的类路径下


2). 配置 hibernate.cfg.xml 

I.   配置启用 hibernate 的二级缓存
true


II.  配置hibernate二级缓存使用的产品
org.hibernate.cache.ehcache.EhCacheRegionFactory


III. 配置对哪些类使用 hibernate 的二级缓存


实际上也可以在 .hbm.xml 文件中配置对哪些类使用二级缓存, 及二级缓存的策略是什么. 


3). 集合级别的二级缓存的配置

I. 配置对集合使用二级缓存 :在hibernate.cfg.xml中配置:



也可以在 .hbm.xml 文件中进行配置



 
            



II. 注意: 还需要配置集合中的元素对应的持久化类也使用二级缓存! 否则将会多出 n 条 SQL 语句. 


4). ehcache 的 配置文件: ehcache.xml


5).  查询缓存: 默认情况下, 设置的缓存对 HQL 及 QBC 查询时无效的, 但可以通过以下方式使其是有效的

I.  在 hibernate 配置文件中声明开启查询缓存

true

II. 调用 Query 或 Criteria 的 setCacheable(true) 方法

III. 查询缓存依赖于二级缓存



关于Struts2 + spring + hibernate进Q群: 130529143交流。
有偿技术支持Q群:
398162181 





你可能感兴趣的:(数据库,JAVA)