一. 知识储备
1.首先要在xml文件中开启tx组件的,然后再配置事务管理器。
2. 在需要用到事务管理的方法或者类前加@Transactional即可
3.如果方法和类都加了@Transactional注解,那么方法优先
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.atguigu.spring.tx"></context:component-scan>
<!-- 连接池 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- <constructor-arg ref="dataSource"></constructor-arg> -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的方式进行事务管理,开启事务注解支持
transaction-manager:指定当前使用的事务管理器
-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
BookShopServiceImpl.java
package com.atguigu.spring.tx.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.spring.tx.dao.BookShopDao;
@Service
public class BookShopServiceImpl implements BookShopService {
@Autowired
private BookShopDao bookShopDao;
@Transactional
@Override
public void buyBook(String username, String isbn) {
// TODO Auto-generated method stub
//1.查书价格
Integer price = bookShopDao.getPriceByIsbn(isbn);
//2. 改书库存
bookShopDao.updateBookStock(isbn);
//3. 改用户余额
bookShopDao.updateAccount(username, price);
}
}