系列文章目录
Spring中事务的处理相关内容的学习
文章目录
- 系列文章目录
- 前言
- 一、Spring事务简介
- 二、案例:银行账户转账
- 1.题目要求和思路分析
- 2.实现步骤
- 3.实现结构
- 三、spring事务角色
- 四、spring事务相关配置
- 五、案例:转账业务追加日志
- 1.题目要求和思路分析
- 2.解决方案和代码实现
- 总结
前言
一、Spring事务简介
二、案例:银行账户转账
1.题目要求和思路分析
2.实现步骤
3.实现结构
项目结构
JdbcConfig
package org.example.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;import javax.sql.DataSource;public class JdbcConfig {@Value("${jdbc.driver}")private String drive;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Beanpublic DataSource dataSource(){DruidDataSource ds=new DruidDataSource();ds.setDriverClassName(drive);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}//配置事务管理器@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();transactionManager.setDataSource(dataSource);return transactionManager;}
}
MybatisConfig
package org.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MybatisConfig {//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("org.example.domain");ssfb.setDataSource(dataSource);return ssfb;}//定义bean,返回MapperScannerConfigurer对象@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc=new MapperScannerConfigurer();msc.setBasePackage("org.example.dao");return msc;}
}
SpringConfig
package org.example.config;import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
AccountDao
package org.example.dao;import org.apache.ibatis.annotations.*;
import org.example.domain.Account;import java.util.List;public interface AccountDao {@Update("update tbl_account set money = money + #{money} where name = #{name}")void inMoney(@Param("name") String name, @Param("money") Double money);@Update("update tbl_account set money = money - #{money} where name = #{name}")void outMoney(@Param("name") String name, @Param("money") Double money);
}
Account
package org.example.domain;public class Account {private Integer id;private String name;private Double money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}
AccountService
package org.example.service;import org.springframework.transaction.annotation.Transactional;public interface AccountService {/*** 转账操作* @param out 转出方* @param in 转入方* @param money 金额*///开启事务@Transactionalpublic void transfer(String out,String in,Double money);
}
AccountServiceImpl
package org.example.service.impl;import org.example.dao.AccountDao;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;public void transfer(String out, String in, Double money) {accountDao.outMoney(out,money);int i=10/0;accountDao.inMoney(in,money);}
}
AccountServiceTest
package org.example.service;import org.example.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;//设定类运行器
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void testTransfer() throws Exception{accountService.transfer("Tom","Jerry",100.0);}
}
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=****
三、spring事务角色
四、spring事务相关配置
有些异常是默认不参加回滚的。只有运行时异常和Error的错误spring会自动回滚,其他异常是不参加回滚,所以要设置事务回滚异常
五、案例:转账业务追加日志
1.题目要求和思路分析
2.解决方案和代码实现
项目结构
LogDao
package org.example.dao;import org.apache.ibatis.annotations.Insert;public interface LogDao {@Insert("insert into tbl_log (info,createDate) values(#{info},now()) ")void log(String info);
}
LogService
package org.example.service;import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;public interface LogService {@Transactional(propagation = Propagation.REQUIRES_NEW)void log(String out,String in,Double money);
}
LogServiceImpl
package org.example.service.impl;import org.example.dao.LogDao;
import org.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class LogServiceImpl implements LogService {@Autowiredprivate LogDao logDao;public void log(String out, String in, Double money) {logDao.log("转账操作由"+out+"到"+in+",金额:"+money);}
}
AccountServiceImpl
package org.example.service.impl;import org.example.dao.AccountDao;
import org.example.service.AccountService;
import org.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Autowiredprivate LogService logService;public void transfer(String out, String in, Double money) {try {accountDao.outMoney(out,money);accountDao.inMoney(in,money);}finally {logService.log(out,in,money);}}
}
其余代码按照上面银行转账的操作进行编写,须注意数据库要新建tbl_log的表。
总结
本节主要讲了spring中对于事务的处理,并分析事务管理的一些小案例
参考视频