- .......
- //对数据库的操作
- public
void update(String name,String password){ -
//业务处理方法 -
//update1(); -
//update2(); - }
- ......
Spring配置文件
- <bean
id="dataSource" -
class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -
<property name="driverClassName"> -
<value>com.microsoft.jdbc.sqlserver.SQLServerDrivervalue> -
property> -
<property name="url"> -
<value>jdbc:microsoft:sqlserver://localhost:1433/xxvalue> -
property> -
<property name="name"> -
<value>usenamevalue> -
property> -
<!-- 设定密码 --> -
<property name="msg"> -
<value>passwordvalue> -
property> - bean>
- <bean
id="transactionManager" -
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> -
<property name="dataSource"> -
<ref bean="dataSource" /> -
property> - bean>
- <bean
id="xxDAOProxy" -
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> -
<property name="transactionManager"> -
<ref bean="transactionManager" /> -
property> -
<property name="target"> -
<ref bean="xxDAO" /> -
property> -
<property name="transactionAttributes"> -
<props> -
<prop key="update*">PROPAGATION_REQUIREDprop> -
props> -
property> - bean>
还有一种配置文件的写法,更加的灵活点。
- <bean
id="transactionInterceptor" -
class="org.springframework.transaction.interceptor.TransactionInterceptor"> -
<property name="transactionManager"> -
<ref bean="transactionManager" /> -
property> -
<property name="transactionAttributeSource"> -
<value>org.eyeqq.DAO.xxDAO.update*=PROPAGATION_REQUIREDvalue> -
property> - bean>
- <bean
id="xxDAOProxy" -
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> -
<property name="interceptorNames"> -
<value>transactionInterceptor,xxDAOvalue> -
property> - bean>
如果使用Hibernate的话那么我们的TransactionManager应该换成这样子。
- <bean
id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> -
<property name="sessionFactory" ref="sessionFactory"/> - </bean>
-
- n
id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -
<property name="dataSource" ref="dataSource" /> -
<property name="mappingResources"> -
<list> -
<value>org.eyeqq.vo.userVO.hbm.xml</value> -
</list> -
</property> -
<property name="hibernateProperties"> -
<props> -
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> -
<prop key="hibernate.show_sql">true</prop> -
</props> -
</property> - </bean>
这样子,只要在service里面调用update方法,Spring就会自动给你完成事务的处理。
XML代码说明:
- <property
name="target"> -
<ref bean="xxDAO" /> - property>
- <property
name="transactionAttributes"> -
<props> -
<prop key="update*">PROPAGATION_REQUIREDprop> -
props> - property>
target属性指定要被TransactionProxyFactoryB
transactionAttributes指定xxDAO中需要实现事务处理的方法。
事务属性值:
PROPAGATION_REQUIRED:如果当前没有事务,就新建一个事务。
PROPAGATION_SUPPORTS:如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY:如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED:以非事务的方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。