@事务性需要定义多次

问题描述 投票:0回答:1

在Spring Boot项目中。 为什么我们需要为这两个方法定义@Transacational。 我有一个方法 saveData(),从中调用另一个方法 saveMethod()。 为什么我们需要在这两种方法中定义@Transactional? 提供代码供参考。

@RestController
@RequestMapping("/api/v1/")
public class CallFunctionController {

    @Autowired
    CustomerRepository customerRepository;

    @Autowired
    EmployeeRepository employeeRepository;

    @GetMapping("/call")
    @Transactional(rollbackFor = SQLIntegrityConstraintViolationException.class)
    public ResponseEntity saveData(){
        saveMethod();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Transactional(rollbackFor = SQLIntegrityConstraintViolationException.class)
    private void saveMethod() {
        Employee employee= new Employee();
        employee.setName("pppppp");
        employee.setDepartmentId(1L);
        employee.setSalary(20L);
        employee.setPerformance("BAD");
        employee.setStatus(true);
        Employee employees= employeeRepository.save(employee);
        Customer customer= new Customer();
     

        customer.setCustomerId(employees.getEmployeeId());
        customer.setActive(employee.getStatus());
        customer.setEmail("[email protected]");
        customer.setPhoneNo("xxxxxxxx");
        customer.setLastName("wwwwwww");
        customerRepository.save(customer);
    }
}

为什么我们需要从savedata()方法和saveMethod()定义@Transactional(rollbackFor = SQLIntegrityConstraintViolationException.class)

database spring-boot spring-data-jpa spring-data spring-transactions
1个回答
0
投票

@Transactional 注解仅适用于直接涉及数据库操作的方法和类。在您的情况下,控制器方法“saveMethod()”上的注释将不起作用。您应该仅在存储库级别的类或方法中使用@Transactional。放在Controller和Service类中不会有任何效果,除非它们是直接调用数据库操作(当然不推荐这种设计模式)。

© www.soinside.com 2019 - 2024. All rights reserved.