Spring小例子转账

代码实现:

1.数据层
public class AccountDao extends JdbcDaoSupport{
	//
	public void addMoney(String name,Double money) {
		String sql = "update bank set money = money + ? where name = ?";
		this.getJdbcTemplate().update(sql,money,name);
		
	}
	public void reduceMoney(String name,Double money) {
		String sql = "update bank set money = money - ? where name = ?";
		this.getJdbcTemplate().update(sql,money,name);
	}
}


2.服务层
public class AccountService {
	/*
	private AccountDao accountDao ;
	private TransactionTemplate template;
	
	public void setTemplate(TransactionTemplate template) {
		this.template = template;
	}

	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}

	public void transfer(final String add,final String reduce,final Double money) {
		TransactionCallback tc = new TransactionCallbackWithoutResult() {
			
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus arg0) {
				accountDao.addMoney(add, money);
				accountDao.reduceMoney(reduce, money);
				
			}
		};
		template.execute(tc);
	}*/
	//上面的与下面代码相同效果,下面使用的是bean注入
	private AccountDao accountDao ;
	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	public Boolean transfer(final String add,final String reduce,final Double money) {
		accountDao.addMoney(add, money);
		accountDao.reduceMoney(reduce, money);
		return true;
	}
}

3.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:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/util 
		http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!--事务对应的通知类定义  -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 定义事务相关的信息 -->
		<tx:attributes>
			<!--哪些方法带有事务必须告诉切面  -->
			<tx:method 
			name="transfer"
			timeout="-1"
			read-only="false"
			isolation="DEFAULT"
			propagation="REQUIRED"
			
			/>
			<!-- <tx:method name="get*" ....这里单独定义属性 get开头方法的属性/> -->
			<!-- <tx:method name="*" 给所有 通知类的方法 加属性/> -->
			
			<!--
			timeout="-1":超时设置
			isolation="DEFAULT" :隔离度的级别
			no-rollback-for="异常类名":遇到这个异常类不回滚,会继续执行
			rollback-for="异常类名" 遇到这个异常类回滚,不会继续执行
			propagation="REQUIRED":事物的传播属性
			  -->
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*.transfer(..))"/>
	</aop:config>
	
	<bean id="accountService" class="com.array.tx.AccountService">
		<property name="accountDao" ref="accountDao"></property>
	</bean>
	
	<bean id="accountDao" class="com.array.tx.AccountDao">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- transactionManager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--jdbc dataSource  -->
	<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
		<property name="username" value="array"></property>
		<property name="password" value="array"></property>
	</bean>
	
	
事务传播行为

4.测试类
public class App {
	public static void main(String[] args) {
		ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext2.xml");
		AccountService accountService = (AccountService) act.getBean("accountService");
		Boolean boolean1 = accountService.transfer("object", "array", 100.00);
		if (boolean1) {
			System.out.println("转账成功");
		}
		
	}
}


假设一个银行系统,其中有两个账户,分别是A和B。现在需要进行一笔转账操作,将A账户中的100元转到B账户中。 以下是使用Spring事务来处理这个转账操作的例子: 1. 建一个AccountService,用于封装转账操作。 ```java @Service public class AccountService { @Autowired private AccountDao accountDao; @Transactional public void transfer(String fromAccount, String toAccount, double amount) { Account from = accountDao.getAccount(fromAccount); Account to = accountDao.getAccount(toAccount); from.setBalance(from.getBalance() - amount); to.setBalance(to.getBalance() + amount); accountDao.updateAccount(from); accountDao.updateAccount(to); } } ``` 2. 建一个AccountDao,用于操作数据库中的账户信息。 ```java @Repository public class AccountDao { @Autowired private JdbcTemplate jdbcTemplate; public Account getAccount(String accountNumber) { return jdbcTemplate.queryForObject("SELECT * FROM accounts WHERE account_number=?", new Object[]{accountNumber}, new AccountRowMapper()); } public void updateAccount(Account account) { jdbcTemplate.update("UPDATE accounts SET balance=? WHERE account_number=?", account.getBalance(), account.getAccountNumber()); } } ``` 3. 建一个Account,用于表示账户信息。 ```java public class Account { private String accountNumber; private double balance; public Account(String accountNumber, double balance) { this.accountNumber = accountNumber; this.balance = balance; } // getters and setters } ``` 4. 建一个AccountRowMapper,用于将数据库中的记录映射到Account对象中。 ```java public class AccountRowMapper implements RowMapper<Account> { @Override public Account mapRow(ResultSet rs, int rowNum) throws SQLException { String accountNumber = rs.getString("account_number"); double balance = rs.getDouble("balance"); return new Account(accountNumber, balance); } } ``` 5. 在Spring配置文件中开启事务管理。 ```xml <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> ``` 6. 编写一个测试,用于验证转账操作是否正确。 ```java @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class AccountServiceTest { @Autowired private AccountService accountService; @Test public void testTransfer() { accountService.transfer("A", "B", 100); Account accountA = accountService.getAccount("A"); Account accountB = accountService.getAccount("B"); Assert.assertEquals(0.0, accountA.getBalance(), 0.01); Assert.assertEquals(100.0, accountB.getBalance(), 0.01); } } ``` 在上述例子中,我们使用了@Transactional注解来标记转账操作,表示这个操作需要在一个事务中执行。如果转账操作中的任何一步失败,整个事务都将被回滚,保证数据的一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值