实践hibernate加spring的整合

     写此文的目的:以后在hibernate和spring 整合的时候就不用再走弯路了;

    

     我这里没用到Struts所以spring的加载就由TOMCAT来完成;

   

      web.xml配置如下:

  1. <listener> 
  2.     <listener-class> 
  3.        org.springframework.web.context.ContextLoaderListener 
  4.     </listener-class> 
  5.          </listener> 
  6. <context-param> 
  7.     <param-name>contextConfigLocation</param-name> 
  8.  <!-- 多个配置文件用逗号隔开 -->
  9.     <param-value>/WEB-INF/springDB.xml,/WEB-INF/FacadeContext.xml</param-value> 
  10.     </context-param>    

       在程序中获取该spring容器的方式:

         

  1.  //获取ServletContext 对象引用,这里的this对象是一个servlet实例。
  2.  ServletContext sc = this.getServletContext();
  3.  ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

      springDB.xml配置文件文件,难点在于事务代理机制的理解,如文件中配置的beanNames属性为 *Dao,意思是在所有以Dao结尾的bean中的find*,delete*,。。。。自动进行代理,对事物进行管理,当你从容器中将该bean取出来时,要用该Dao实现的接口来进行类型转换(jdk动态代理的理解),

 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
  3. <beans default-autowire="no" default-dependency-check="none" default-lazy-init="false">
  4.     <!-- ========================= Start of PERSISTENCE DEFINITIONS ========================= -->
  5.     <!-- Hibernate SessionFactory Definition-->
  6.    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  7.         <!-- localhost 默认的配置-->
  8.             <property name="location">
  9.             <value>/hibernates.properties</value>
  10.         </property>
  11.     </bean>
  12. <!-- 需要引入proxool-0.9.0RC3.jar  ehcache-1.2.jar(与二级缓存相关)-->
  13.    <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">   
  14.             <property name="driver">
  15.                 <value>${jdbc.driver}</value>
  16.             </property>
  17.             <property name="driverUrl">
  18.                <value>${jdbc.url}</value>
  19.             </property>
  20.           
  21.             <property name="user">
  22.                <value>${jdbc.username}</value>
  23.             </property>
  24.         
  25.             <property name="password">
  26.                <value>${jdbc.password}</value>
  27.             </property> 
  28.             <property name="alias">
  29.                <value>${jdbc.alias}</value>
  30.               </property>   
  31.             <property name="houseKeepingSleepTime">
  32.                <value>${jdbc.houseKeepingSleepTime}</value>
  33.             </property>
  34.             <property name="prototypeCount">
  35.                <value>${jdbc.prototypeCount}</value>
  36.             </property>
  37.             <property name="maximumConnectionCount">
  38.                <value>${jdbc.maximumConnectionCount}</value>
  39.             </property>
  40.             <property name="minimumConnectionCount">
  41.                <value>${jdbc.minimumConnectionCount}</value>
  42.             </property>
  43.             <property name="maximumConnectionLifetime">
  44.                <value>${proxool.maximumConnectionLifetime}</value>
  45.             </property>
  46.             <property name="maximumActiveTime">
  47.                <value>${proxool.maximumActiveTime}</value>
  48.             </property>
  49.         
  50.             <property name="trace">
  51.                <value>${jdbc.trace}</value>
  52.             </property>
  53.             <property name="verbose">
  54.                <value>${jdbc.verbose}</value>
  55.             </property>  
  56.             <property name="houseKeepingTestSql">
  57.                  <value>${proxool.houseKeepingTestSql}</value> 
  58.              </property>
  59.              <property name="statistics">
  60.                  <value>${proxool.statistics}</value> 
  61.              </property>
  62.              <property name="statisticsLogLevel">
  63.                  <value>${proxool.statisticsLogLevel}</value> 
  64.              </property>
  65.        
  66.             </bean>    
  67.             
  68.      <!-- 第二中配置方式,单独的类似dbcp的使用 ,配置结束-->   
  69.     <!-- Hibernate SessionFactory Definition:定义Hibernate的SessionFactory -->
  70.     <!-- use spring sessionFactory of configurtion -->
  71.     <!-- 定义了Hibernate的会话工厂,会话工厂类用Spring提供的LocalSessionFactoryBean维护,它注入了数据源dataSource和资源映射文件com/cfc/bo,此外还通过一些键值对设置了Hibernate所需的属性 -->
  72.     <bean id="sessionFactory"
  73.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  74.         
  75.         <property name="dataSource">
  76.             <ref local="dataSource" />
  77.         </property>
  78.         <property name="mappingDirectoryLocations">
  79.             <!-- 在此可以匹配*.hbm.xml映射文件 -->
  80.             <list>
  81.                 <value>classpath:/com/cfc/web/pojo</value>
  82.             </list>
  83.         </property>
  84.          <!-- 定义Hibernate的SessionFactory属性 -->
  85.         <property name="hibernateProperties">
  86.             <props>
  87.                 <prop key="hibernate.dialect">
  88.                     ${hibernate.dialect}
  89.                 </prop>
  90.                 <prop key="hibernate.show_sql">
  91.                     ${hibernate.show_sql}
  92.                 </prop>
  93.                 <prop key="hibernate.format_sql">
  94.                     ${hibernate.format_sql}
  95.                 </prop>
  96.                 <prop key="hibernate.jdbc.fetch_size">
  97.                     ${hibernate.jdbc.fetch_size}
  98.                 </prop>
  99.                 <prop key="hibernate.jdbc.batch_size">  
  100.                     ${hibernate.jdbc.batch_size}
  101.                 </prop>
  102.             
  103.                 <!-- second cache -->
  104.                 <!--  使用ehcache,适合项目用 
  105.                 <prop key="hibernate.cache.use_query_cache">
  106.                     ${hibernate.cache.use_query_cache}
  107.                 </prop>
  108.                 <prop key="hibernate.cache.use_second_level_cache">
  109.                     ${hibernate.cache.use_second_level_cache}
  110.                 </prop>
  111.                 <prop key="hibernate.cache.provider_class">
  112.                     ${hibernate.cache.provider_class}
  113.                 </prop> 
  114.                 -->
  115.                 <!--   
  116. 此处要注意因为proxool自己释放数据库连接比慢,所以要在此给出释放连接的模式,具体几种模式对应的意思,可以Google一下hibernate.connection.release_mode,有很多说明,在此不多说  
  117.                --> 
  118.                
  119.                 <prop key="hibernate.connectionReleaseMode">  
  120.                     ${hibernate.connectionReleaseMode}   
  121.                 </prop>  
  122.                 <prop key="simultaneous-build-throttle">
  123.                    ${simultaneous-build-throttle}
  124.                  </prop>
  125.                  <prop key="jdbc.maximumnewConnections">
  126.                     ${jdbc.maximumnewConnections}
  127.                  </prop>
  128.                  <prop key="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</prop>
  129.                  <prop key="hibernate.proxool.existing_pool">false</prop>
  130.                  <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
  131.                  
  132.                  
  133.             </props>
  134.         </property>
  135.     </bean>
  136.     
  137.     <!-- Hibernate Transaction Manager Definition :配置Hibernate的事务管理器-->     
  138.     <bean id="transactionManager"
  139.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  140.         <!-- HibernateTransactionManager Bean,它需要依赖注入一个SessionFactory
  141.         Bean的引用 -->
  142.         <property name="sessionFactory">
  143.             <ref bean="sessionFactory" />
  144.         </property>
  145.     </bean>
  146.     <!-- jdbcTemplate  -->
  147.     <!-- 这个基础类来实战连接Mysql数据库.JdbcTemplate的使用需要有一个DataSource的支持,所以在配置文件中,
  148.          我们首先要配置一个Spring的DriverManagerDataSource,然后将这个DataSource配置到JdbcTemplate里.
  149.          接着将JdbcTemplate配置到DAO层.最后将DAO配置到Model层 -->
  150.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">   
  151.         <property name="dataSource">
  152.         <ref bean="dataSource" />
  153.         </property> 
  154.         </bean>   
  155.     <!-- Hibernate Template Defintion -->
  156.     <bean id="hibernateTemplate"
  157.         class="org.springframework.orm.hibernate3.HibernateTemplate">
  158.         <property name="sessionFactory">
  159.             <ref bean="sessionFactory" />
  160.         </property>
  161.         <property name="jdbcExceptionTranslator">
  162.             <ref bean="jdbcExceptionTranslator" />
  163.         </property>
  164.     </bean>
  165.     <!-- Spring Data Access Exception Translator Defintion -->
  166.     <bean id="jdbcExceptionTranslator"
  167.         class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
  168.         <property name="dataSource">
  169.             <ref bean="dataSource" />
  170.         </property>
  171.     </bean>
  172.     <!-- define transaction interceptor -->
  173.     <bean id="txInterceptor"
  174.         class="org.springframework.transaction.interceptor.TransactionInterceptor">
  175.         <property name="transactionManager">
  176.             <ref bean="transactionManager" />
  177.         </property>
  178.         <property name="transactionAttributeSource">
  179.             <ref bean="txAttributes" />
  180.         </property>
  181.     </bean>
  182.     <bean id="autoProxyCreator"
  183.         class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  184.         <property name="interceptorNames">
  185.             <value>txInterceptor</value>
  186.         </property>
  187.         <!--这里通过配置文件,引用bean有数据库的操作。也可以直接在这个文件中配置。本项目中是分开配置,即FacadeContext.xml文件 -->
  188.         <property name="beanNames">
  189.             <value>*Dao,*Service</value>
  190.         </property>
  191.     </bean>
  192.     <bean id="txAttributes"
  193.         class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
  194.         <property name="properties">
  195.             <value>
  196.                 find*=PROPAGATION_REQUIRED,readOnly
  197.                 get*=PROPAGATION_REQUIRED,readOnly
  198.                 save*=PROPAGATION_REQUIRED
  199.                 add*=PROPAGATION_REQUIRED
  200.                 insert*=PROPAGATION_REQUIRED
  201.                 update*=PROPAGATION_REQUIRED
  202.                 delete*=PROPAGATION_REQUIRED 
  203.                 create*=PROPAGATION_REQUIRED
  204.                 batch*=PROPAGATION_REQUIRED
  205.                 generate*=PROPAGATION_REQUIRED
  206.             </value>
  207.         </property>
  208.     </bean>
  209. </beans>

hibernate.proterty文件代码

  1. #database driver
  2. jdbc.driver=com.mysql.jdbc.Driver
  3. #url:这里一定要这样写,否则报错:Access denied for user 'root'@'localhost' (using password: NO)
  4. #jdbcjdbc.url=jdbc:mysql://192.168.1.54:3306/tdscdmanew?useUnicode=truecharacterEncoding=UTF-8user=rootpassword=root
  5. jdbcjdbc.url=jdbc:mysql://192.168.1.252:3306/tscdmaweb?useUnicode=truecharacterEncoding=UTF-8user=rootpassword=root
  6. #jdbcjdbc.url=jdbc:mysql://192.168.1.252:3306/tdscdmanew?useUnicode=truecharacterEncoding=UTF-8user=rootpassword=root
  7. #login database info
  8. #如果用proxool配置,这两个属性不用,但是必须这样写,这是个BUG
  9. jdbc.username=root  
  10. jdbc.password=root
  11. #hibernate properties
  12. hibernate.dialect=org.hibernate.dialect.MySQLDialect
  13. #Batch Size is set to the database to delete bulk, bulk and bulk insert update when the batch size
  14. hibernate.jdbc.batch_size=25
  15. #Fetch Size is set to read Statement of JDBC data from the database each time out of the number of records
  16. hibernate.jdbc.fetch_size=50
  17. hibernate.show_sql=true
  18. hibernate.format_sql=true
  19. #second level cache open configuration
  20. #hibernate.cache.use_query_cache=true
  21. #hibernate.cache.use_second_level_cache=true
  22. #hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
  23. #pool configuration
  24. #pool alias
  25. jdbc.alias=dbcptmclnew
  26. #proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁
  27. jdbc.houseKeepingSleepTime=90000
  28. # 指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受 proxool.maximumnewconnections=20
  29. jdbc.maximumnewConnections=5
  30. #最少保持的空闲连接数(默认2个).一次产生连接的数量。 但不能超过最大连接数
  31. jdbc.prototypeCount=3
  32. #允许最大连接数,超过了这个连接,再有请求时,就排在队列中等候,最大的等待请求数由maximum-new-connections决定 (默认5个)
  33. #如果超过最大连接数量则会抛出异常。连接数设置过多,服务器CPU和内存性能消耗很大。
  34. jdbc.maximumConnectionCount=100
  35. #最小连接数 (默认2个).建议设置0以上,保证第一次连接时间
  36. jdbc.minimumConnectionCount=5
  37. #最大活动时间(超过此时间线程将被kill,默认为5分钟,10)
  38. proxool.maximumActiveTime = 60000000
  39. #连接最长时间(默认为8小时:28000s),一个线程的最大寿命
  40. proxool.maximumConnectionLifetime=18000000
  41. #
  42. #hibernate.bytecode.use_reflection_optimizer=true
  43. #允许被缓存的JDBC连接开启
  44. #因为proxool自己释放数据库连接比慢,所以要在此给出释放连接的模式.AFTER_STATEMENT (也被称做积极释放) - 在每一条语句被执行后就释放连接。但假若语句留下了与session相关的资源,那就不会被释放
  45. #hibernate.connectionReleaseMode=after_statement
  46. hibernate.connectionReleaseMode=auto
  47. #
  48. simultaneous-build-throttle=10
  49. #trace为true,记录数据库每一步操作
  50. jdbc.trace=true
  51. #verbose:If this is true then we start logging a lot of stuff everytime we serve a connection and everytime the house keeper and prototyper run. Be prepared for a lot of debug!  
  52. #记录执行的详细信息
  53. jdbc.verbose=true
  54. #
  55. proxool.houseKeepingTestSql=select CURRENT_DATE
  56. #统计的时隔可以分为s(econds),、m(inutes)、h(ours)与d(ays),就下面的设定来说,就是15秒、10分钟、1天分别作统计
  57. proxool.statistics=15s,10m,1d
  58. #INFO,ERROR
  59. proxool.statisticsLogLevel=INFO

      

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章