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;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		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 实战
以上只是学习所做的笔记, 以供日后参考!!!

猜你喜欢

转载自blog.csdn.net/z1790424577/article/details/81128148