[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

一、实验目的:

熟练掌握声明式事务管理。

二、实验内容:

编写一个模拟银行转账的程序,要求在转账时通过Spring对事务进行控制。

三、实验要求:

分别使用基于XML和基于注解的声明式事务管理方式来实现。

四、设计

1.数据表设计:id money name

2.Dao数据库层:
根据用户的id查询用户的余额信息
根据用户的id查询的姓名
根据id存钱
根据id取钱

3.service层:
根据用户的id查询用户的余额信息
A给B转账(调用 根据id存钱、根据id取钱)
其内调用(根据用户的id查询的姓名)来展示用户转账过程

4.controller层:
控制层(调用服务层方法,并在控制层完成事务操作的异常处理)

5.测试层:
XMLTest.java:
调用托管在Spring里的控制层方法,获取到控制层返回的结果信息
XML方式:在XML里面利用AOP的操作,切点是Service,通知就是其事务的操作

AnnotationTest.java:
调用托管在Spring里的控制层方法,获取到控制层返回的结果信息
基于注释:利用@Transactional在service方法处进行事务管理,在xml内扫描标签

五、代码

BankDao.java

package com.dao;
public interface BankDao {
	public double getMoneyById(String id);
	public String getNameById(String id);
	public void cashIn(String id, double money);
	public void cashOut(String id, double money);
}

BankDaoImpl.java

package com.dao;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.util.MyException;

//@Repository用于标注数据访问组件,即DAO组件
@Repository("BankDao")

/*
 * 数据访问层
 */
public class BankDaoImpl implements BankDao {
	
	
	        
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	//根据用户的id查询用户的余额信息
	public double getMoneyById(String id) {
		String sql="select money from bank where id=?";
		return jdbcTemplate.queryForObject(sql, new Object[] {id}, double.class);
	}
	
	@Override
	//根据用户的id查询的姓名
	public String getNameById(String id) {
		String sql="select name from bank where id=?";
		return jdbcTemplate.queryForObject(sql, new Object[] {id}, String.class);
	}
	
	@Override
	//根据id存钱
	public void cashIn(String id, double money) {
		String sql="update bank set money=money+? where id=?";
		jdbcTemplate.update(sql, money,id);	
	}
	
	
	@Override
	//根据id取钱
	public void cashOut(String id, double money) {

		double num=getMoneyById(id);//查询余额
		if(num>=money) {
			//余额充足,可以取钱
			String sql="update bank set money=money-? where id=?";
			jdbcTemplate.update(sql, money,id);
		}else {
			//余额不足,向外抛出异常
			System.out.println("余额不足");
			throw new MyException("余额不足");
	
		}
		

	}
	
		
	
}

BankService.java

package com.service;

public interface BankService {
	
	public void transferMoney(String inId,String outId, double money);

}

BankServiceImpl.java

package com.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.BankDao;
import com.util.MyException;
@Service("BankService")

/*
 * 服务层(对数据访问层封装,绑定事务操作)
 */

public class BankServiceImpl implements BankService{
	@Autowired
	private BankDao bankdao;
	
	//基于注释的事务管理
	@Transactional(rollbackFor = (MyException.class))
//	这里调用Dao层的save和delete方法,参数为sql和param,等控制层在传入sql语句
	public void transferMoney(String inId,String outId, double money) {
		
		String name1 = bankdao.getNameById(inId);
		String name2 = bankdao.getNameById(outId);
		
		double money1 = bankdao.getMoneyById(inId);
		double money2 = bankdao.getMoneyById(outId);
		
		
		
		System.out.println("转账前:"+name2+"的余额:"+ money2 +"   "+ name1+"余额:"+ money1);
		
		//转账的具体操作
		bankdao.cashIn(inId, money);
		bankdao.cashOut(outId, money);
		
		double money3 = bankdao.getMoneyById(inId);
		double money4 = bankdao.getMoneyById(outId);
		
		System.out.println("用户1:"+name2+" >>>==转账==>>> "+ "用户2:"+ name1);
		System.out.println("支付宝到账:"+ money + "元");
		System.out.println("转账后:"+name2+"的余额:"+ money4 +"   "+ name1+"余额:"+ money3);
		
		
	}
	
}

BankController.java

package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.service.BankService;

@Controller("BankController")

/*
 * 控制层(调用服务层方法,并在控制层完成事务操作的异常处理)
 */
public class BankController {
	
	@Autowired
	private BankService bankService;
	public String test() {
		
		String message = "";
		
		try{
			bankService.transferMoney("002","001", 5);
			
			message = "事务正常";
			
			
		}catch(Exception e){
			
			message = "事务异常,回滚";
			e.printStackTrace();
			
		}
		return message;
	}
}

(一)基于XML的声明式事务管理方式
XMLTest.java

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.controller.BankController;

/*
 * 测试类(调用托管在Spring里的控制层方法,获取到控制层返回的结果信息)
 * 
 * XML方式:在XML里面利用AOP的操作,切点是Service,通知就是其事务的操作
 */

public class XMLTest {
	public static void main(String[] args) {
		
		@SuppressWarnings("resource")
		ApplicationContext appCon = new ClassPathXmlApplicationContext("/com/xml/XMLstatementapplicationContext.xml");
		BankController ct = (BankController)appCon.getBean("BankController");
		
		String result = ct.test();
		System.out.println(result);
	}
}

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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 指定需要扫描的包(包括子包),使注解生效 -->
   <context:component-scan base-package="com"/>
   <!-- 配置数据源 -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   		<!-- MySQL数据库驱动 -->
   		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
   		<!-- 连接数据库的URL -->
   		<property name="url" value="jdbc:mysql://localhost:3306/bank?characterEncoding=utf8"/>
   		<!-- 连接数据库的用户名 -->
   		<property name="username" value="root"/>
   		<!-- 连接数据库的密码 -->
   		<property name="password" value="363316495"/>
   </bean>
   <!-- 配置JDBC模板 -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
   		<property name="dataSource" ref="dataSource"/>
   </bean>
   <!-- 为数据源添加事务管理器 -->
   <bean id="txManager"   
	     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
	     <property name="dataSource" ref="dataSource" />   
   </bean> 
   
   <!-- 编写通知:声明事务 -->
   <tx:advice id="myAdvice" transaction-manager="txManager">
   		<tx:attributes>
   			<!--事务的传播行为  -->
			<tx:method name="*" propagation="REQUIRED"/>

   		</tx:attributes>
   </tx:advice>
   
   
   <!-- 编写AOP,让Spring自动对目标对象生成代理,需要使用AspectJ的表达式 -->
   <aop:config>
   		<!-- 定义切入点,织入的对象是testService -->
   		<aop:pointcut expression="execution(* com.service.*.*(..))" id="txPointCut"/>
   		<!-- 切面:将切入点与通知关联 -->
   		<aop:advisor advice-ref="myAdvice" pointcut-ref="txPointCut"/>
   </aop:config>
</beans>

(二)基于注解的声明式事务管理方式

AnnotationTest.java

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.controller.BankController;

/*
 * 测试类(调用托管在Spring里的控制层方法,获取到控制层返回的结果信息)
 * 
 * 基于注释:利用@Transactional在service方法处进行事务管理,在xml内扫描标签
 */

public class AnnotationTest {
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext appCon = new ClassPathXmlApplicationContext("/com/xml/annotationstatementapplicationContext.xml");
		BankController ct = (BankController)appCon.getBean("BankController");
		String result = ct.test();
		System.out.println(result);
	}
}

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:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 指定需要扫描的包(包括子包),使注解生效 -->
   <context:component-scan base-package="com"/>
   <!-- 配置数据源 -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   		<!-- MySQL数据库驱动 -->
   		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
   		<!-- 连接数据库的URL -->
   		<property name="url" value="jdbc:mysql://localhost:3306/bank?characterEncoding=utf8"/>
   		<!-- 连接数据库的用户名 -->
   		<property name="username" value="root"/>
   		<!-- 连接数据库的密码 -->
   		<property name="password" value="363316495"/>
   </bean>
   <!-- 配置JDBC模板 -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
   		<property name="dataSource" ref="dataSource"/>
   </bean>
   <!-- 为数据源添加事务管理器 -->
   <bean id="txManager"   
	     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
	     <property name="dataSource" ref="dataSource" />   
   </bean> 
   <!-- 为事务管理器注册注解驱动 -->
   <tx:annotation-driven transaction-manager="txManager" />
</beans>

六、结果

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

[JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序