002 springBoot事物

  在使用注解的时候,需要注意的是,只能写在@Service的类中才能生效。

1.事物

  只是需要一个注解即可

2.事物程序

 1 package com.caojun.springboot;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 import org.springframework.transaction.annotation.Transactional;
 6 
 7 @Service
 8 public class TransactionService {
 9 
10     @Autowired
11     private StudentResitory studentResitory;
12 
13     @Transactional
14     public void insertTwo(){
15         Student student1=new Student();
16         student1.setName("AA");
17         student1.setAge(33);
18         studentResitory.save(student1);
19 
20         Student student2=new Student();
21         student2.setName("BB");
22         student2.setAge(44);
23         studentResitory.save(student2);
24     }
25 }

3.验证程序

 1 @RestController
 2 public class StudentController {
 3 
 4     @Autowired
 5     private StudentResitory studentResitory;
 6 
 7     @Autowired
 8     private TransactionService transactionService;
 9 
10     /**
11      * 数据库事物
12      */
13     @GetMapping(value = "/hello/insertTwo")
14     public void insertStu(){
15         transactionService.insertTwo();
16     }

4.效果

  

原文地址:https://www.cnblogs.com/juncaoit/p/7806645.html