註解管理的方式要比xml配置方式要簡單不少mysql
只需在配置文件中添加事務註解spring
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context.xsd 12 http://www.springframework.org/schema/tx 13 http://www.springframework.org/schema/tx/spring-tx.xsd 14 http://www.springframework.org/schema/aop 15 http://www.springframework.org/schema/aop/spring-aop.xsd "> 16 17 <!-- 配置c3p0鏈接池 --> 18 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 19 <!-- 注入dao對象 --> 20 <property name="driverClass" value="com.mysql.jdbc.Driver"></property> 21 <property name="jdbcUrl" value="jdbc:mysql:///test"></property> 22 <property name="user" value="root"></property> 23 <property name="password" value="jqbjqbjqb123"></property> 24 </bean> 25 26 <bean id="orderService" class="cn.service.OrderService"> 27 <property name="orderDao" ref="orderDao"></property> 28 </bean> 29 <bean id="orderDao" class="cn.dao.OrderDao"> 30 <!-- 注入jdbcTemplate對象--> 31 <property name="jdbcTemplate" ref="jdbcTemplate"></property> 32 </bean> 33 34 <!-- 建立jdbcTemplate對象 --> 35 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 36 <!-- 把dataSource傳遞到模板對象中--> 37 <property name="dataSource" ref="dataSource"></property> 38 </bean> 39 40 <!-- 第一步:配置事務管理器 --> 41 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 42 <!-- 注入dataSource --> 43 <property name="dataSource" ref="dataSource"></property> 44 </bean> 45 46 <!-- 第二步:開啓事務註解 --> 47 <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> 48 49 </beans>
而後在邏輯業務類上加上註解@Transactional 便可sql
1 package cn.service; 2 3 import cn.dao.OrderDao; 4 import org.springframework.transaction.annotation.Transactional; 5 6 @Transactional 7 public class OrderService { 8 private OrderDao orderDao; 9 10 public void setOrderDao(OrderDao orderDao) { 11 this.orderDao = orderDao; 12 } 13 14 //調用dao的方法 15 //業務邏輯層,寫轉帳業務 16 public void accountMoney(){ 17 //狗蛋轉帳給建國,在帳面上看就是狗蛋減錢,建國多錢 18 //狗蛋減錢 19 orderDao.lessMoney(); 20 int i = 10/0; 21 //建國多錢 22 orderDao.moreMoney(); 23 } 24 }
可防止不明錯誤致使數據產生不一致。less