spring提供的事务配置--纯注解
spring提供的事务--纯注解

模拟转账业务 ,出错需要事务回滚,没错正常执行

事务和数据库技术都是spring的内置提供的
--------dao包---------------
IAccountDao接口
package com.dao; import com.domain.Account; /**
*
* @date 2019/11/6 15:25
*/
public interface IAccountDao {
Account findAllById(Integer id);
Account findAccountByName(String name);
void updateAccount(Account account);
}
IAccountDao实现类
package com.dao.impl; import com.dao.IAccountDao;
import com.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; import java.util.List; /**
* 账户实现类
* @date 2019/11/6 15:27
*/
@Repository("accountDao")
public class IAccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate template; @Override
public Account findAllById(Integer id) {
List<Account> query = template.query("select * from account where id= ?", new BeanPropertyRowMapper<>(Account.class), id);
return query.isEmpty()?null:query.get(0);
} @Override
public Account findAccountByName(String name) {
List<Account> accounts = template.query("select * from account where name= ?", new BeanPropertyRowMapper<>(Account.class),name);
if (accounts.isEmpty()){
return null;
}
if (accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
} @Override
public void updateAccount(Account account) {
template.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
--------domain包--------
domain类
package com.domain; import java.io.Serializable; /**
*
* @date 2019/11/5 21:32
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money; @Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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 Float getMoney() {
return money;
} public void setMoney(Float money) {
this.money = money;
}
}
--------service包---------------
IAccountService类
package com.service; import com.domain.Account; /**
* 账户业务层
* @date 2019/11/7 9:26
*/
public interface IAccountService {
//根据id查询账户信息
Account findAllById(Integer integer);
/*转账
* 转出账户,转入账户,转账金额*/
void transfer(String sourceName, String targetName, Float f);
}
AccountServiceImpl类
package com.service.impl; import com.dao.IAccountDao;
import com.domain.Account;
import com.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; /**
* 账户的业务层实现类
*
* 事务控制应该都是在业务层
*/
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao; /*
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
*/ @Override
public Account findAllById(Integer accountId) {
return accountDao.findAllById(accountId); } @Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source); // int i=1/0; //2.6更新转入账户
accountDao.updateAccount(target);
}
}
AccountServiceImpl
--------config包---------------
JdbcConfig类
package config; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; /**
* 数据库配置类
* @date 2019/11/7 15:10
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password; @Bean(name = "jdbcTemplate")
public JdbcTemplate createTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDatasource(){
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
JdbcConfig
SpringConfig类
package config; import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement; /**
* spring的配置类 相当于bean.xml
* @date 2019/11/7 15:08
*/
@Configuration
@ComponentScan("com") //扫描包
@Import({JdbcConfig.class,TransactionManager.class})
@PropertySource("jdbcConfig.properties") //配置数据源
@EnableTransactionManagement //开启注解支持
public class SpringConfig {
}
SpringConfig
TransactionManager类
package config; import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; /**
* 配置事务管理器
* @date 2019/11/7 15:41
*/
public class TransactionManager {
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource source){
return new DataSourceTransactionManager(source);
}
}
--------配置文件---------------
jdbcConfig.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db5
jdbc.username=root
jdbc.password=123
--------test包---------------
AccountServiceTest类
import com.service.IAccountService;
import 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; /**
* 使用spring jdbcTemplate 和内置的事务管理实现转账的业务
* 基于注解
* @date 2019/11/7 9:44
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest { @Autowired
private IAccountService as; @Test
public void testTransfer(){
as.transfer("a","b",100f);
} }
--------pom---------------
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency> <dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
pom文件
支付宝到账100元!

spring提供的事务配置--纯注解的更多相关文章
- aop注解 spring提供的事务
http://www.cnblogs.com/friends-wf/p/3826893.html 是 自定义的切面,并且添加注解 声明为切面 利用spring提供的事务声明 主要在 service层上 ...
- Spring系列之事务的控制 注解实现+xml实现+事务的隔离等级
Spring系列之事务的控制 注解实现+xml实现 在前面我写过一篇关于事务的文章,大家可以先去看看那一篇再看这一篇,学习起来会更加得心应手 链接:https://blog.csdn.net/pjh8 ...
- Spring AOP及事务配置三种模式详解
Spring AOP简述 Spring AOP的设计思想,就是通过动态代理,在运行期对需要使用的业务逻辑方法进行增强. 使用场景如:日志打印.权限.事务控制等. 默认情况下,Spring会根据被代理的 ...
- Spring 中的事务操作、注解、以及 XML 配置
事务 事务全称叫数据库事务,是数据库并发控制时的基本单位,它是一个操作集合,这些操作要么不执行,要么都执行,不可分割.例如我们的转账这个业务,就需要进行数据库事务的处理. 转账中至少会涉及到两条 SQ ...
- Spring管理 hibernate 事务配置的五种方式
Spring配置文件中关于事务配置总是由三个组成部分,DataSource.TransactionManager和代理机制这三部分,无论是那种配置方法,一般变化的只是代理机制这块! 首先我创建了两个类 ...
- Spring声明式事务配置详解
Spring支持编程式事务管理和声明式的事务管理. 编程式事务管理 将事务管理代码嵌到业务方法中来控制事务的提交和回滚 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码 声明式事务管理 一般情 ...
- Spring学习8-Spring事务管理(注解式声明事务管理)
步骤一.在spring配置文件中引入<tx:>命名空间 <beans xmlns="http://www.springframework.org/schema/beans& ...
- spring、mybatis事务配置和控制
springmybatis.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi= ...
- spring 提供了哪些配置方式?
基于 xml 配置 bean 所需的依赖项和服务在 XML 格式的配置文件中指定.这些配置文件通常 包含许多 bean 定义和特定于应用程序的配置选项.它们通常以 bean 标签开 头. 例如: &l ...
随机推荐
- Java--Runtime.addShutdownHook
转自:http://kim-miao.iteye.com/blog/1662550 一.Runtime.addShutdownHook理解 在看别人的代码时,发现其中有这个方法,便顺便梳理一下. vo ...
- redis 会丢数据吗
不管是以前的主从模式(哨兵模式),还是现在的集群模式,因为都用了slave of 同步; 而slave of 同步会丢弃本地数据,直接用对方的数据来覆盖本地,所以会丢失数据 1.主备网络不通,后续主节 ...
- JavaScript详解(二)
js的流程控制 if语句: if (条件表达式A){ xx; }else if (条件表达式B){ xx; } else{ xx; } switch语句: switch (表达式){ case 值1: ...
- 黑马eesy_15 Vue:04.Vue案例(ssm环境搭建)
黑马eesy_15 Vue:02.常用语法 黑马eesy_15 Vue:03.生命周期 黑马eesy_15 Vue:04.Vue案例(ssm环境搭建) 黑马eesy_15 Vue:04.综合案例(前端 ...
- Multiple alleles|an intuitive argument|
I.5 Multiple alleles. 由两个等位基因拓展到多个等位基因,可以得到更多种二倍体基因型: 所以单个等位基因的概率(用i代指某个基因,pi*是该基因的频率)是(以计数的方法表示) 所以 ...
- AI大火之下智能手机行业能适应这一风口吗?
今年智能手机行业的变化,实在是让人摸不到头脑.一方面是智能手机厂商依然在拿出各种具有噱头的产品,仿佛整个市场还依然热火朝天.但在另一方面,智能手机出货量却出现大幅下滑.据中国信息通信研究院发布的数据显 ...
- mediawiki资料
1.如何通过ip访问mediawiki --- http://blog.sina.com.cn/s/blog_3f2a2b8e01000awx.html 发布到外部网络,更改htfp.config里面 ...
- Q_Go2
一.变量 1.1 变量的概念 变量是计算机语言中存储数据的抽象概念.变量的功能是存储数据.变量通过变量名访问. 变量的本质是计算机分配的一小块内存,专门用于存放指定数据,在程序运行过程中该数值可以发生 ...
- python3下scrapy爬虫(第十四卷:scrapy+scrapy_redis+scrapyd打造分布式爬虫之执行)
现在我们现在一个分机上引入一个SCRAPY的爬虫项目,要求数据存储在MONGODB中 现在我们需要在SETTING.PY设置我们的爬虫文件 再添加PIPELINE 注释掉的原因是爬虫执行完后,和本地存 ...
- Mysql Sql 语句练习题 (50道)
MySql 语句练习50题 表名和字段 –1.学生表 Student(s_id,s_name,s_birth,s_sex) –学生编号,学生姓名, 出生年月,学生性别 –2.课程表 Course(c_ ...