日期:2014-05-16  浏览次数:20439 次

启用事务的spring与jdbc集成_AOP代理

JdbcTemplate没有内置事务机制

可以使用Spring的AOP代理机制来实现

具体实现:
配置文件

<!-- 数据源对象 -->
<bean id="datasrc" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
 <property name="username" value="root"></property>
 <property name="password" value=""></property>
 <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
</bean>
<!-- JdbcTemplate对象 -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
 <property name="dataSource" ref="datasrc"></property>
</bean>
<!-- 实现类的对象 -->  
<bean id="userdaoimpl" class="com.dowebber.dao.impl.UserDaoImpl">
 <property name="jdt" ref="jdbctemplate"></property>
</bean>
<!-- 配置transactionManager -->
<bean id="transmgr" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="datasrc"></property>
</bean>
<!-- 配置代理对象 -->
<bean id="userdaoproxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
 <property name="target" ref="userdaoimpl"></property>
 <property name="proxyInterfaces" value="com.dowebber.dao.UserDao"></property>
 <property name="transactionManager" ref="transmgr"></property>
 <property name="transactionAttributes">
  <props>
   <prop key="*User">PROPAGATION_REQUIRED,-Exception</prop>
  </props>
 </property>
</bean>

?
transactionAttributes:如果配置多个事务中间可以用逗号分开
-Exception:表示代码出现异常,事务不提交
+Exception:表示代码出现异常,事务也提交
<prop key="*User">PROPAGATION_REQUIRED,-Exception</prop>
<1>:如果key的值为*,说明所有的方法都加事务
<2>:也可以通配匹配 *User


测试?? 不知如何测试...