Spring Boot的数据访问(三)事务

简介

使用Spring Boot默认的配置就能满足我们绝大多数需求。

实战

1:新建Spring Boot项目,添加依赖JPA和Web,并导入数据库驱动
2:配置属性
application.properties

//数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/book
spring.datasource.username=root
spring.datasource.password=123456

//JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent-output=true

实体类Person

@Entity
public class Person {
	@Id 
	@GeneratedValue
	private Long id;
	
	private String name;
	
	private Integer age;
	
	private String address;
	
	
	public Person() {
		super();
	}
	public Person(Long id, String name, Integer age, String address) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}

}

实体类Repository

public interface PersonRepository extends JpaRepository<Person, Long> {
	
}

服务接口

public interface DemoService {
	public Person savePersonWithRollBack(Person person);
	public Person savePersonWithoutRollBack(Person person);

}

服务接口的实现

@Service
public class DemoServiceImpl implements DemoService {
	@Autowired
	PersonRepository personRepository; //注入PersonRepository
	
	@Transactional(rollbackFor={IllegalArgumentException.class}) //使用rollbackFor属性,指定异常回滚
	public Person savePersonWithRollBack(Person person){
		Person p =personRepository.save(person);

		if(person.getName().equals("汪云飞")){
			throw new IllegalArgumentException("汪云飞已存在,数据将回滚"); //手动触发异常
		}
		return p;
	}

	@Transactional(noRollbackFor={IllegalArgumentException.class}) //使用noRollbackFor属性,指定异常不回滚
	public Person savePersonWithoutRollBack(Person person){
		Person p =personRepository.save(person);
		
		if(person.getName().equals("汪云飞")){
			throw new IllegalArgumentException("汪云飞虽已存在,数据将不会回滚");
		}
		return p;
	}
}

控制器MyController

@RestController
public class MyController {
	@Autowired
	DemoService demoService;
	
	@RequestMapping("/rollback")
	public Person rollback(Person person){ //测试回滚
		
		return demoService.savePersonWithRollBack(person);
	}
	
	@RequestMapping("/norollback")
	public Person noRollback(Person person){//测试不回滚
		
		return demoService.savePersonWithoutRollBack(person);	
	}

}

运行测试:

以Debug方式访问 http://localhost:8080/rollback?name=汪云飞&age=32

这里写图片描述
可以发现数据已保存且id为122.继续执行将抛出异常,导致数据回滚!
这里写图片描述
数据库并没有新增数据:
这里写图片描述

访问 http://localhost:8080/norollback?name=汪云飞&age=32

这里写图片描述
但数据并没有回滚,且数据库新增了一条记录:
这里写图片描述

参考书籍:Spring Boot 实战
以上只是学习所做的笔记, 以供日后参考!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值