Java本地应用使用spring及hibernate

本文详细介绍了如何在Spring框架中整合Hibernate,包括配置数据源、会话工厂、事务管理等核心组件,并展示了不同配置方式的具体实现。

ApplicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"   
  3. "http://www.springframework.org/dtd/spring-beans.dtd">  
  4.   
  5. <beans>  
  6.   
  7.     <!-- =================================================================== -->  
  8.     <!-- Context Define                                                      -->  
  9.     <!-- =================================================================== -->        
  10.     <bean  
  11.         id="propertyConfigurer"  
  12.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  13.         <property name="locations">  
  14.             <list>  
  15.                 <value>classpath:conf/hibernate.properties</value>  
  16.             </list>  
  17.         </property>   
  18.     </bean>  
  19.       
  20.     <!-- =================================================================== -->  
  21.     <!-- Data Source Define                                                  -->  
  22.     <!-- =================================================================== -->  
  23.        
  24.       
  25.     <bean   
  26.         id="dataSource"   
  27.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  28.         <property name="driverClassName" value="${hibernate.connection.driver_class}"/>  
  29.         <property name="url" value="${hibernate.connection.url}"/>  
  30.         <property name="username" value="${hibernate.connection.username}"/>  
  31.         <property name="password" value="${hibernate.connection.password}"/>  
  32.     </bean>  
  33.           
  34.     <!-- =================================================================== -->  
  35.     <!-- Hibernate Session Define                                            -->  
  36.     <!-- =================================================================== -->    
  37.     <bean   
  38.         id="sessionFactory"   
  39.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  40.         <property name="dataSource" ref="dataSource"/>          
  41.         <property name="hibernateProperties">  
  42.             <props>  
  43.                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
  44.                 <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>  
  45.                 <prop key="hibernate.cache.use_query_cache">true</prop>  
  46.                 <!-- prop key="hibernate.jdbc.batch_size">0</prop>  
  47.                 <prop key="hibernate.connection.pool_size">3</prop -->  
  48.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
  49.                 <prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop>  
  50.             </props>  
  51.         </property>  
  52.         <property name="lobHandler" ref="${jdbc.handler}"/>  
  53.     </bean>  
  54.       
  55.     <bean  
  56.         id="oracleLobHandler"  
  57.         class="org.springframework.jdbc.support.lob.OracleLobHandler">  
  58.         <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>  
  59.     </bean>     
  60.       
  61.     <bean  
  62.         id="defaultLobHandler"  
  63.         class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true">  
  64.     </bean>     
  65.       
  66.     <bean   
  67.         id="nativeJdbcExtractor"   
  68.         class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor"   
  69.         lazy-init="true"  
  70.     />  
  71.       
  72.     <!-- =================================================================== -->  
  73.     <!-- Transaction Define                                                  -->  
  74.     <!-- =================================================================== -->  
  75.     <bean   
  76.         id="transactionManager"   
  77.         class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
  78.         <property name="sessionFactory" ref="sessionFactory"/>  
  79.     </bean>  
  80.       
  81.     <bean  
  82.         id="basicTxProxy" abstract="true"  
  83.         class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">  
  84.         <property name="transactionManager" ref="transactionManager"/>  
  85.         <property name="transactionAttributes">  
  86.             <props>  
  87.                 <prop key="save*">PROPAGATION_REQUIRED</prop>  
  88.                 <prop key="add*">PROPAGATION_REQUIRED</prop>  
  89.                 <prop key="remove*">PROPAGATION_REQUIRED</prop>  
  90.                 <prop key="update*">PROPAGATION_REQUIRED</prop>  
  91.                 <prop key="*">PROPAGATION_REQUIRED</prop>  
  92.             </props>  
  93.         </property>  
  94.     </bean>  
  95. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

	<!-- =================================================================== -->
	<!-- Context Define                                                      -->
	<!-- =================================================================== -->		
	<bean
		id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:conf/hibernate.properties</value>
			</list>
		</property> 
	</bean>
	
	<!-- =================================================================== -->
	<!-- Data Source Define                                                  -->
	<!-- =================================================================== -->
	 
	
	<bean 
		id="dataSource" 
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${hibernate.connection.driver_class}"/>
		<property name="url" value="${hibernate.connection.url}"/>
		<property name="username" value="${hibernate.connection.username}"/>
		<property name="password" value="${hibernate.connection.password}"/>
	</bean>
		
	<!-- =================================================================== -->
	<!-- Hibernate Session Define                                            -->
	<!-- =================================================================== -->	
	<bean 
		id="sessionFactory" 
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>		
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
				<prop key="hibernate.cache.use_query_cache">true</prop>
				<!-- prop key="hibernate.jdbc.batch_size">0</prop>
				<prop key="hibernate.connection.pool_size">3</prop -->
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.query.factory_class">${hibernate.query.factory_class}</prop>
			</props>
		</property>
		<property name="lobHandler" ref="${jdbc.handler}"/>
	</bean>
	
	<bean
		id="oracleLobHandler"
		class="org.springframework.jdbc.support.lob.OracleLobHandler">
		<property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>
	</bean>	
	
	<bean
		id="defaultLobHandler"
		class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true">
	</bean>	
	
	<bean 
		id="nativeJdbcExtractor" 
		class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor" 
		lazy-init="true"
	/>
	
	<!-- =================================================================== -->
	<!-- Transaction Define                                                  -->
	<!-- =================================================================== -->
	<bean 
		id="transactionManager" 
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<bean
		id="basicTxProxy" abstract="true"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="transactionManager"/>
		<property name="transactionAttributes">
			<props>
				<prop key="save*">PROPAGATION_REQUIRED</prop>
				<prop key="add*">PROPAGATION_REQUIRED</prop>
				<prop key="remove*">PROPAGATION_REQUIRED</prop>
				<prop key="update*">PROPAGATION_REQUIRED</prop>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
</beans>

datasource的另一种配置方式:jndi

  1. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">  
  2. <property name="jndiName" value="jdbc/stptdemo"/>  
  3. </bean>  
		<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="jdbc/stptdemo"/>
		</bean>



hibernate.properties:

  1. ######################  
  2. ### Query Language ###  
  3. ######################  
  4.   
  5. ## define query language constants / function names  
  6. hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'  
  7.   
  8. ##Hibernate 2.1 query parser (for Weblogic 8.1)  
  9. #hibernate.query.factory_class org.hibernate.hql.classic.ClassicQueryTranslatorFactory  
  10.   
  11. ##Hibernate 3.0 query parser   
  12. hibernate.query.factory_class org.hibernate.hql.ast.ASTQueryTranslatorFactory  
  13.   
  14. ###########################  
  15. ### C3P0 Connection Pool###  
  16. ###########################  
  17.   
  18. #hibernate.c3p0.max_size 2  
  19. #hibernate.c3p0.min_size 2  
  20. #hibernate.c3p0.timeout 5000  
  21. #hibernate.c3p0.max_statements 100  
  22. #hibernate.c3p0.idle_test_period 3000  
  23. #hibernate.c3p0.acquire_increment 2  
  24. ##hibernate.c3p0.validate false  
  25.   
  26. #################################  
  27. ### Hibernate Connection Pool ###  
  28. #################################  
  29.   
  30. hibernate.connection.pool_size 1  
  31. hibernate.show_sql true  
  32. hibernate.format_sql false  
  33.   
  34. ##############################  
  35. ### Proxool Connection Pool###  
  36. ##############################  
  37.   
  38. ## Properties for external configuration of Proxool  
  39. hibernate.proxool.pool_alias pool1  
  40.   
  41. ##############################  
  42. ### Miscellaneous Settings ###  
  43. ##############################  
  44.   
  45. ## set the maximum JDBC 2 batch size (a nonzero value enables batching)  
  46. hibernate.jdbc.batch_size 0  
  47.   
  48. ## use streams when writing binary types to / from JDBC  
  49. hibernate.jdbc.use_streams_for_binary true  
  50.   
  51. ## set the maximum depth of the outer join fetch tree  
  52. hibernate.max_fetch_depth 1  
  53.   
  54. ##########################  
  55. ### Second-level Cache ###  
  56. ##########################  
  57.   
  58. ## enable the query cache  
  59. ## hibernate.cache.use_query_cache true  
  60.   
  61. ## choose a cache implementation  
  62. hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider  
  63.   
  64. #################  
  65. ### Platforms ###  
  66. #################  
  67.   
  68. ## Oracle  
  69. jdbc.handler oracleLobHandler  
  70. #jdbc.handler defaultLobHandler  
  71.   
  72. hibernate.dialect org.hibernate.dialect.Oracle9Dialect  
  73. hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver  
  74. hibernate.connection.username stpt  
  75. #hibernate.connection.password stpt.db.209  
  76. hibernate.connection.password shSTpt  
  77. hibernate.connection.url jdbc:oracle:thin:@10.1.41.101:1521:orcl  
  78. #hibernate.connection.url jdbc:oracle:thin:@10.1.44.209:1521:orcl  
  79. #hibernate.connection.url jdbc:oracle:thin:@10.1.43.11:1521:stnic1  
  80.   
  81. ## SQLServer  
  82.   
  83. #hibernate.dialect org.hibernate.dialect.SQLServerDialect  
  84. #hibernate.connection.driver_class net.sourceforge.jtds.jdbc.Driver  
  85. #hibernate.connection.url jdbc:jtds:sqlserver://localhost:1433/CuteFramework  
  86. #hibernate.connection.username sa  
  87. #hibernate.connection.password sa  
  88.   
  89. ## Informix  
  90.   
  91. #hibernate.dialect org.hibernate.dialect.Informix9Dialect  
  92. #hibernate.connection.driver_class com.informix.jdbc.IfxDriver  
  93. #hibernate.connection.username uaas  
  94. #hibernate.connection.password uaas  
  95. #hibernate.connection.url jdbc:informix-sqli://10.3.11.12:7515/uaas:INFORMIXSERVER=k460secsoc  
  96.   
  97. ## DB2  
  98.   
  99. #hibernate.dialect org.hibernate.dialect.DB2Dialect  
  100. #hibernate.connection.driver_class com.ibm.db2.jcc.DB2Driver  
  101. #hibernate.connection.username db2admin  
  102. #hibernate.connection.password db2admin  
  103. #hibernate.connection.url jdbc:db2://wjh:50000/frame  
  104.   
  105. ## DO NOT specify hibernate.connection.sqlDialect  
######################
### Query Language ###
######################

## define query language constants / function names
hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'

##Hibernate 2.1 query parser (for Weblogic 8.1)
#hibernate.query.factory_class org.hibernate.hql.classic.ClassicQueryTranslatorFactory

##Hibernate 3.0 query parser 
hibernate.query.factory_class org.hibernate.hql.ast.ASTQueryTranslatorFactory

###########################
### 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

#################################
### Hibernate Connection Pool ###
#################################

hibernate.connection.pool_size 1
hibernate.show_sql true
hibernate.format_sql false

##############################
### Proxool Connection Pool###
##############################

## Properties for external configuration of Proxool
hibernate.proxool.pool_alias pool1

##############################
### Miscellaneous Settings ###
##############################

## set the maximum JDBC 2 batch size (a nonzero value enables batching)
hibernate.jdbc.batch_size 0

## use streams when writing binary types to / from JDBC
hibernate.jdbc.use_streams_for_binary true

## set the maximum depth of the outer join fetch tree
hibernate.max_fetch_depth 1

##########################
### Second-level Cache ###
##########################

## enable the query cache
## hibernate.cache.use_query_cache true

## choose a cache implementation
hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider

#################
### Platforms ###
#################

## Oracle
jdbc.handler oracleLobHandler
#jdbc.handler defaultLobHandler

hibernate.dialect org.hibernate.dialect.Oracle9Dialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.username stpt
#hibernate.connection.password stpt.db.209
hibernate.connection.password shSTpt
hibernate.connection.url jdbc:oracle:thin:@10.1.41.101:1521:orcl
#hibernate.connection.url jdbc:oracle:thin:@10.1.44.209:1521:orcl
#hibernate.connection.url jdbc:oracle:thin:@10.1.43.11:1521:stnic1

## SQLServer

#hibernate.dialect org.hibernate.dialect.SQLServerDialect
#hibernate.connection.driver_class net.sourceforge.jtds.jdbc.Driver
#hibernate.connection.url jdbc:jtds:sqlserver://localhost:1433/CuteFramework
#hibernate.connection.username sa
#hibernate.connection.password sa

## Informix

#hibernate.dialect org.hibernate.dialect.Informix9Dialect
#hibernate.connection.driver_class com.informix.jdbc.IfxDriver
#hibernate.connection.username uaas
#hibernate.connection.password uaas
#hibernate.connection.url jdbc:informix-sqli://10.3.11.12:7515/uaas:INFORMIXSERVER=k460secsoc

## DB2

#hibernate.dialect org.hibernate.dialect.DB2Dialect
#hibernate.connection.driver_class com.ibm.db2.jcc.DB2Driver
#hibernate.connection.username db2admin
#hibernate.connection.password db2admin
#hibernate.connection.url jdbc:db2://wjh:50000/frame

## DO NOT specify hibernate.connection.sqlDialect


也可在 hibernate.cfg.xml中配置:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  3.   
  4. <!-- NOTE: For Hibernate Session Factory Use Only -->  
  5. <hibernate-configuration>   
  6.   <session-factory>   
  7.     <property name="connection.pool_size">1</property>    
  8.     <property name="show_sql">false</property>    
  9.     <property name="format_sql">true</property>    
  10.     <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>    
  11.     <property name="cache.use_query_cache">true</property>    
  12.     <property name="query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>    
  13.     <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>    
  14.     <property name="proxool.pool_alias">pool1</property>    
  15.     <property name="connection.SetBigStringTryClob">true</property>    
  16.     <property name="jdbc.batch_size">0</property>    
  17.     <property name="jdbc.use_streams_for_binary">true</property>    
  18.     <property name="max_fetch_depth">1</property>    
  19. </session-factory>   
  20. </hibernate-configuration>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- NOTE: For Hibernate Session Factory Use Only -->
<hibernate-configuration> 
  <session-factory> 
    <property name="connection.pool_size">1</property>  
    <property name="show_sql">false</property>  
    <property name="format_sql">true</property>  
    <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property>  
    <property name="cache.use_query_cache">true</property>  
    <property name="query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>  
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>  
    <property name="proxool.pool_alias">pool1</property>  
    <property name="connection.SetBigStringTryClob">true</property>  
    <property name="jdbc.batch_size">0</property>  
    <property name="jdbc.use_streams_for_binary">true</property>  
    <property name="max_fetch_depth">1</property>  
</session-factory> 
</hibernate-configuration>
文件applicaitonContext.xml中sessionfactory bean中增加属性 :

  1. <property name="configLocation"  
  2.             value="classpath:hibernate.cfg.xml" />  
<property name="configLocation"
			value="classpath:hibernate.cfg.xml" />
读取配置。


main.java

  1. /** 
  2.  * spring上下文 
  3.  */  
  4. ApplicationContext applicationContext = null;  
  5.   
  6. /** 
  7.  * 初始化spring上下文 
  8.  */  
  9. protected void initAppContext() {  
  10.     String[] fileUrl = new String[]{"classpath*:conf/*Context*.xml"};  
  11.     applicationContext = new ClassPathXmlApplicationContext(fileUrl);  
  12. }  
	/**
	 * spring上下文
	 */
	ApplicationContext applicationContext = null;

	/**
	 * 初始化spring上下文
	 */
	protected void initAppContext() {
		String[] fileUrl = new String[]{"classpath*:conf/*Context*.xml"};
		applicationContext = new ClassPathXmlApplicationContext(fileUrl);
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值