實踐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

      

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