`
cuisuqiang
  • 浏览: 3954245 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
3feb66c0-2fb6-35ff-968a-5f5ec10ada43
Java研发技术指南
浏览量:3665217
社区版块
存档分类
最新评论

Spring 配置 事务的几种方式

    博客分类:
  • SSH
阅读更多

Spring配置文件中关于事务配置总是由三个组成部分,DataSource、TransactionManager和代理机制这三部分,无论是那种配置方法,一般变化的只是代理机制这块!

 

首先我创建了两个类,一个接口一个实现:

package com.dao;
public interface UserDao {
	public void getUser();	
}

 

实现:

package com.dao.impl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.dao.UserDao;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	public void getUser(){		
	}	
}

 

 

第一种:每个Bean都有一个代理:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://192.168.0.244:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="20" />
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="10" />
		<property name="defaultAutoCommit" value="true" />
	</bean>
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/nms/entity/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQL5Dialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>    
    <!-- 定义事务管理器 -->  
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>    
    <!-- 配置服务层 -->
    <bean id="userDaoAgency" class="com.dao.impl.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>    
    <bean id="userDao"  
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">  
        <!-- 配置事务管理器 -->  
        <property name="transactionManager" ref="transactionManager" />     
        <property name="target" ref="userDaoAgency" />  
        <property name="proxyInterfaces" value="com.dao.UserDao" />
        <!-- 配置事务属性 -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>
            </props>  
        </property>  
    </bean>
</beans>

 

 

第二种:所有Bean共享一个代理:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://192.168.0.244:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="20" />
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="10" />
		<property name="defaultAutoCommit" value="true" />
	</bean>
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/nms/entity/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQL5Dialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	<!-- 定义事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	 <!-- 定义事务 -->
	<bean id="base"
		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
		lazy-init="true" abstract="true">
		<!-- 配置事务管理器 -->
		<property name="transactionManager" ref="transactionManager" />
		<!-- 配置事务属性 -->
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED</prop>
			</props>
		</property>
	</bean>
	<!-- 配置服务层 -->
	<bean id="userDao"
		class="com.dao.impl.UserDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 代理对象 -->
	<bean id="userDaoAgency" parent="base">
		<property name="target" ref="userDao" />
	</bean>
</beans>

 

 

第三种:拦截器:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://192.168.0.244:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="20" />
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="10" />
		<property name="defaultAutoCommit" value="true" />
	</bean>
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/nms/entity/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQL5Dialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>    
     <!-- 定义事务管理器(声明式的事务) -->  
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>   
     <!-- 定义事务 --> 
    <bean id="transactionInterceptor"  
        class="org.springframework.transaction.interceptor.TransactionInterceptor">  
        <property name="transactionManager" ref="transactionManager" />  
        <!-- 配置事务属性 -->  
        <property name="transactionAttributes">  
            <props>  
                <prop key="*">PROPAGATION_REQUIRED</prop>  
            </props>  
        </property>  
    </bean>      
    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
        <property name="beanNames">  
            <list>  
                <value>*DaoImpl</value>
            </list>  
        </property>  
        <property name="interceptorNames">  
            <list>  
                <value>transactionInterceptor</value>  
            </list>  
        </property>  
    </bean>  
    <!-- 配置服务层 -->
    <bean id="userDaoAgency" class="com.dao.impl.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

 

 

第四种:使用tx标签配置的拦截器:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://192.168.0.244:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="20" />
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="10" />
		<property name="defaultAutoCommit" value="true" />
	</bean>
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/nms/entity/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQL5Dialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	<context:annotation-config />
	<context:component-scan base-package="com.dao" />
	<!-- 定义事务管理器 -->  
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- 定义事务 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <!-- 定义切面 -->
    <aop:config>
        <aop:pointcut id="interceptorPointCuts" expression="execution(* com.dao.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
    </aop:config>
</beans>

 

 

第五种:注解:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://192.168.0.244:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="10" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="20" />
		<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="10" />
		<property name="defaultAutoCommit" value="true" />
	</bean>
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/nms/entity/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQL5Dialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
	</bean>
	<context:annotation-config />
	<!-- 使用注解的包路径 -->
	<context:component-scan base-package="com.dao" />
	<!-- 支持  @Transactional 标记 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	<!-- 定义事务管理器 -->  
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

 

如果使用了注解,那么实现类应该这样写:

package com.dao.impl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDao;
@Transactional
@Component("userDaoAgency")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
	/**
	 * 为方法增加事务处理特性
	 */
	@Transactional(readOnly=true)
	public void getUser(){		
	}	
}

 

这样每个方法都能自己定义自己的事务处理!

 

请您到ITEYE看我的原创:http://cuisuqiang.iteye.com

或支持我的个人博客,地址:http://www.javacui.com

 

以上内容,是从网络找到的资料总结而来,仅供参考!

分享到:
评论
3 楼 MrCrapBag 2013-02-18  
恩,写的很详细,赞一个。
2 楼 fangcao5 2013-01-05  
很详细,辛苦了
1 楼 cc1321234545 2012-05-09  
楼主辛苦了

相关推荐

    Spring事务原理、Spring事务配置的五种方式

    Spring事务原理是指Spring框架中的一种机制,用于管理事务,并提供了多种配置方式。事务是指一系列的操作,作为一个整体执行,如果其中某个操作失败,整个事务将回滚。Spring事务原理围绕着两个核心:...

    spring几种事务配置详解【精】

    本文将深入探讨Spring中的几种事务配置方式,帮助开发者更好地理解和运用。 1. **编程式事务管理** 编程式事务管理是在代码中显式调用事务API来控制事务的开始、提交、回滚等操作。这种方式直接在业务逻辑代码中...

    Spring事务配置的五种方式

    Spring 事务配置的五种方式 Spring 框架中的事务配置是一种复杂的机制,涉及到多个组件的协作和配置。通过深入研究 Spring 的事务配置,可以总结出五种不同的配置方式,每种方式都有其特点和适用场景。 第一种方式...

    spring事务几种传播方式

    ### Spring事务传播方式详解 #### 一、引言 在基于Spring框架开发的应用程序中,事务管理是一项重要的功能。为了确保数据的一致性和完整性,合理地配置事务的传播行为至关重要。Spring提供了多种事务传播行为选项...

    Spring事务五种不同的代理配置

    第一种方式需要手动配置事务规则,而第二、三种方式通过注解简化了配置,第四种方式适用于不依赖接口的情况,第五种方式则提供了最大的灵活性。在实际开发中,我们通常会选择基于注解的声明式事务管理,因为它既简洁...

    Spring事务管理的几种配置方式,

    在Spring框架中,事务管理是核心功能之一,它确保了数据操作的一致性和完整性。Spring提供了多种事务管理配置方式,适合不同的应用场景...无论哪种方式,了解其原理和使用场景对于开发高效、可靠的Spring应用至关重要。

    Spring配置的5种方式

    ### Spring配置的5种方式详解 #### 一、引言 在Java开发领域,特别是针对企业级应用,Spring框架作为一款轻量级的容器管理工具,不仅提供了强大的依赖注入功能,还支持多种事务管理策略。Struts2+Spring+Hibernate...

    Spring基于XML方式配置事务

    在Spring配置文件中,我们需要引入`tx`命名空间,并声明一个`PlatformTransactionManager`实例,例如,对于基于JDBC的事务管理,我们会使用`&lt;bean id="transactionManager" class="org.springframework.jdbc....

    Spring事务管理Demo

    首先,Spring提供了两种主要的事务管理方式:编程式事务管理和声明式事务管理。 1. **编程式事务管理**:通过使用`PlatformTransactionManager`接口及其实现类(如`JdbcTemplate`或`HibernateTemplate`),开发者...

    spring事务与数据库操作

    2. **引入Spring配置文件**:接着,在Spring的配置文件中引入AOP约束。 3. **编写目标类**:创建需要增强的目标类(如ProductDao)。 4. **配置目标类**:在Spring配置文件中配置目标类。 5. **开启AOP注解自动代理*...

    spring事务操作试验

    在Spring事务中,有几种常见的隔离级别可供选择,包括读未提交(READ UNCOMMITTED)、读已提交(READ COMMITTED)、可重复读(REPEATABLE READ)和串行化(SERIALIZABLE)。每种隔离级别都有其特定的并发控制策略,...

    spring声明式事务管理配置方式

    - 在传统的Spring配置中,你可以通过`&lt;tx:annotation-driven&gt;`元素启用声明式事务管理,并指定事务管理器。例如: ```xml &lt;bean id="transactionManager" class="org.springframework.jdbc.datasource....

    spring声明式事务配置

    根据提供的信息,我们可以深入探讨Spring框架中的声明式事务配置及其...无论是哪种方式,Spring框架都为声明式事务管理提供了强大的支持,极大地简化了事务处理的过程,使得开发人员能够更加专注于核心业务逻辑的编写。

    Spring 事务配置的五种方式.docx

    在某些复杂应用中,可能需要结合使用上述几种方式。例如,对于一些核心服务使用注解驱动的事务管理,而对于其他辅助服务则采用编程式事务管理。 在配置事务时,通常需要先定义数据源(DataSource),如使用阿里...

    Spring事务管理失效原因汇总

    Spring提供了声明式事务管理和编程式事务管理两种方式,其中声明式事务管理因其实现简单而被广泛应用。声明式事务主要通过Spring AOP(面向切面编程)来实现,它允许在方法执行前后添加事务逻辑而不改变原有代码逻辑。...

    Spring3配置声明式事务

    Spring框架提供了两种事务管理方式:编程式事务管理和声明式事务管理。其中声明式事务管理通过配置来实现事务管理,大大简化了代码量,提高了开发效率。在Spring3中,配置声明式事务变得更为简便,只需几行配置文件...

    spring 事务代理配置

    除了使用`TransactionProxyFactoryBean`,Spring还提供了其他几种声明式事务管理配置方式,包括: 1. **使用注解(@Transactional)**:这是最常见的声明式事务管理方式,通过在方法或类上添加`@Transactional`注解...

    spring几种Dao支持配置

    以下将详细阐述Spring对DAO支持的几种配置方式: 1. **JDBC DAO支持:** Spring通过`JdbcTemplate`和`SimpleJdbcInsert`等类提供了对JDBC的抽象,减少了直接使用JDBC代码的繁琐性。`JdbcTemplate`提供了一组模板...

    Spring事务管理配置

    Spring的事务管理分为编程式和声明式两种方式。编程式事务管理通过在代码中显式地调用`beginTransaction()`、`commit()`和`rollback()`等方法来控制事务边界;而声明式事务管理则通过配置元数据(如XML或注解)来...

Global site tag (gtag.js) - Google Analytics