介绍:我们日常开发中很常用的就是spring的事务管理,我们通常使用声明式事务
声明式事务:基于AOP面向切面的,它将具体业务与事务处理部分解耦,代码侵入性很低,所以在实际开发中声明式事务用的比较多。声明式事务也有两种实现方式,是基于TX和AOP的xml配置文件方式,二种就是基于@Transactional注解了,现在我们通常使用注解的方式
使用场景:@Transactional 可以作用在接口、类、类方法,我们通常使用在方法上
作用:当作用于方法上时,此 public 方法将具有该类型的事务属性,也就是此方法对于数据库操作,要么都成功,要么都不成功(遇到报错会回滚)
正常效果及其展示:
package com.example.springdemo.controller;
import com.example.springdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/getUsers")
public List
package com.example.springdemo.service;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
//@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class TestService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional
public List> getDbType(){
testTransAction();
String sql = "select * from test";
List> list = jdbcTemplate.queryForList(sql);
for (Map map : list) {
Set> entries = map.entrySet( );
if(entries != null) {
Iterator> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Map.Entry entry =(Map.Entry) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
public void testTransAction() {
try {
int update = jdbcTemplate.update("INSERT INTO `test` (`name`, `job`) VALUES ('zhangsan3', 'worker4');");
int a = 1/0;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
当项目启动 执行http://localhost:8080/getUsers后
数据库没有录入数据,证明注解生效,回滚成功
失效的方式:
1.一个有@Transactional的方法被没有@Transactional方法调用时
比如将@Transactional移动到具体的操作数据库的方法
执行后 发现回滚失败
2.@Transactional修饰的方法为非public方法
3.catch了异常 处理完没有抛出异常
经测试,没有回滚
4.rollbackFor设置原因rollbackFor设置了之后,事务只会在指定的设置下生效
5.数据库引擎不支持事务比如 mysql的 innodb支持 但是myisam不支持



