1、通过xml的方式配置事务的步骤:
①配置bean
②配置事务管理器
③配置事务属性
④配置事务切入点,关联事务切入点和事务属性
2、通过xml的方式配置事务相比通过注解的方式配置事务来讲,不需要配置annotation注解和@AutoWire注解和@Transaction注解,使用起来更加方便,只需要配置Spring配置文件
3、使用步骤:
①编写Bean和事务逻辑方法
②编写配置文件,配置bean
③编写配置文件,配置事务管理器
④编写配置文件,配置事务属性
⑤编写配置文件,配置事务切入点,关联事务切入点和事务属性,相当于@Transaction(需要加入AOP命名空间属性)
⑥编写代码,定义和获取IOC容器
⑦编写代码,获取JdbcTemplate对象,Spring配置会根据配置文件自动连接到数据库
⑧编写代码,使用JdbcTemplate对象的逻辑方法
4、文件
①TestMain.java:测试类
②MyException.java:自定义错误抛出类
③TxDao.java:更新账户信息的方法接口
④TxDaoImpl.java:更新账户信息的实现类
⑤ProductDao.java:更新商品信息的方法接口
⑥ProductDaoImpl.java:更新商品信息的实现类
⑦SummaryPruchase.java:交易接口(根据交易信息,调用账户信息和商品信息的更新方法实现类)
⑧SummaryPruchaseImpl.java:交易接口实现类
⑨db.properties:数据库配置信息
⑩jdbcTemplateContextXML.xml:配置文件
5、TestMain.java
package com.demo.sshtestXML;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
/*
通过xml的方式配置事务的步骤:
1、配置bean
2、配置事务管理器
3、配置事务属性
4、配置事务切入点,关联事务切入点和事务属性
*/
public class TestMain {
private static ApplicationContext applicationContext = null;
private static JdbcTemplate jdbcTemplate;
private static ProductDao productDao = null;
private static TxDao txDao=null;
private static SummaryPurchase summaryPurchase=null;
public static void main(String[] args) {
try{
testConnection();
//testTX();
testTransactionPropagation();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
//获取相关配置文件,连接数据库
public static void testConnection() throws SQLException{
applicationContext = new ClassPathXmlApplicationContext("jdbcTemplateContextXML.xml");
DataSource dataSource = applicationContext.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
}
//测试事务
public static void testTX(){
txDao = (TxDao)applicationContext.getBean(TxDao.class);
txDao.pruchase(1, 1, 2);
}
//测试事务传播性
public static void testTransactionPropagation(){
summaryPurchase = (SummaryPurchase)applicationContext.getBean("summaryPurchase");
Map<Integer,Integer> productMap = new HashMap<Integer,Integer>();
productMap.put(1, 1);
productMap.put(2, 1);
productMap.put(3, 1);
summaryPurchase.sPurchase1(1, productMap);
summaryPurchase.sPurchase2(1, productMap);
}
}
6、MyException.java
package com.demo.sshtestXML;
public class MyException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
public MyException() {
super();
}
public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
}
7、TxDao.java
package com.demo.sshtestXML;
public interface TxDao {
public void pruchase(int buterId,int productId,int quantity);
public void pruchaseREQUIRES_NEW(int buterId, int productId, int quantity);
}
8、TxDaoImpl.java
package com.demo.sshtestXML;
public class TxDaoImpl implements TxDao{
public ProductDao getProductDao() {
return productDao;
}
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
private ProductDao productDao;
public void pruchase(int buterId, int productId, int quantity) {
//1、获取单价
double price = productDao.findPricebyProductPriceID(productId);
System.out.println("productId:"+productId+" -> product price:"+price);
//2、更新库存
productDao.updateProductQuantity(productId,quantity);
//3、更新账户余额
productDao.AccountPurchase(buterId,price,quantity);
System.out.println("buyer pruchase");
}
public void pruchaseREQUIRES_NEW(int buterId, int productId, int quantity) {
//1、获取单价
double price = productDao.findPricebyProductPriceID(productId);
System.out.println("productId:"+productId+" -> product price:"+price);
//2、更新库存
productDao.updateProductQuantity(productId,quantity);
//3、更新账户余额
productDao.AccountPurchase(buterId,price,quantity);
System.out.println("buyer pruchase");
}
}
9、ProductDao.java
package com.demo.sshtestXML;
public interface ProductDao {
public double findPricebyProductPriceID(int id);
public void updateProductQuantity(int id,int quantity);
public void AccountPurchase(int id,double price,int quantity);
}
10、ProductDaoImpl.java
package com.demo.sshtestXML;
import org.springframework.jdbc.core.JdbcTemplate;
public class ProductDaoImpl implements ProductDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public double findPricebyProductPriceID(int id) {
String sql = "select price from product where id=?";
return jdbcTemplate.queryForObject(sql,double.class,id);
}
public void updateProductQuantity(int id, int quantity) {
String sqlCheck = "select quantity from product where id=?";
int Check_quantity = jdbcTemplate.queryForObject(sqlCheck,Integer.class,id);
if(Check_quantity<quantity){
throw new MyException("not enough quantity");
}
String sql = "update product set quantity=quantity-? where id=?";
jdbcTemplate.update(sql,quantity,id);
}
public void AccountPurchase(int id, double price, int quantity) {
String sqlCheck = "select balance from account where id=?";
int Check_balance = jdbcTemplate.queryForObject(sqlCheck,Integer.class,id);
if(Check_balance<(price*quantity)){
throw new MyException("not enough balance");
}
String sql = "update account set balance=balance-?*? where id=?";
jdbcTemplate.update(sql,price,quantity,id);
}
}
11、SummaryPruchase.java
package com.demo.sshtestXML;
import java.util.Map;
public interface SummaryPurchase {
public void sPurchase1(int buyerId,Map<Integer, Integer>productMap);
public void sPurchase2(int buyerId,Map<Integer, Integer>productMap);
}
12、SummaryPruchaseImpl.java
package com.demo.sshtestXML;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class SummaryPurchaseImpl implements SummaryPurchase {
private TxDao txDao;
public TxDao getTxDao() {
return txDao;
}
public void setTxDao(TxDao txDao) {
this.txDao = txDao;
}
public void sPurchase1(int buyerId, Map<Integer, Integer> productMap) {
System.out.println("propagation=Propagation.REQUIRED");
for (Map.Entry<Integer, Integer> entry : productMap.entrySet()) {
txDao.pruchase(buyerId, entry.getKey(), entry.getValue());
}
}
public void sPurchase2(int buyerId, Map<Integer, Integer> productMap) {
System.out.println("propagation=Propagation.REQUIRES_NEW");
for (Map.Entry<Integer, Integer> entry : productMap.entrySet()) {
txDao.pruchaseREQUIRES_NEW(buyerId, entry.getKey(), entry.getValue());
}
}
}
13、db.properties
jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost/SpringTest
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10
14、jdbcTemplateContextXML.xml
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.demo.sshtest"></context:component-scan>
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置C3P0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 1、配置bean -->
<bean id="productDao" class="com.demo.sshtestXML.ProductDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="txDao" class="com.demo.sshtestXML.TxDaoImpl">
<property name="productDao" ref="productDao"></property>
</bean>
<bean id="summaryPurchase" class="com.demo.sshtestXML.SummaryPurchaseImpl">
<property name="txDao" ref="txDao"></property>
</bean>
<!-- 2、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 3、配置事务属性 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 根据方法名指定事务的属性 -->
<tx:method name="pruchaseREQUIRES_NEW" propagation="REQUIRES_NEW"/>
<!-- 根据以find开头的方法名来指定事务属性 -->
<tx:method name="find*" readonly="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 4、配置事务切入点,关联事务切入点和事务属性,相当于@Transaction(需要加入AOP命名空间属性) -->
<aop:config>
<aop:pointcut expression="execution(* com.demo.sshtestXML.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config>
</beans>
15、项目目录
16、demo
https://download.csdn.net/download/qq_22778717/10483461