我们什么时候应该使用@Transactional注解?

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

我想知道我们到底什么时候应该在 Spring Boot 服务中使用

@Tranasactional

既然 JpaRepository 的

save()
方法带有
@Tranasactional
注释,我真的需要在我的服务方法中添加该注释吗?

我看过几篇文章说,如果您的服务方法中仅使用存储库(如下面的场景),则不需要将

@Transactional
放在服务方法上,因为
save()
已经用
@Transactional 注释
。是真的吗?

class EmployeeService {

    @Autowired
    EmployeeRepository repo;
    
    @Transactional //(Is it required here?)
    public void saveEmployee(Employee employee) {
    
    repo.save(employee)
    
 }
    
    }

既然我们使用了多个存储库,那么在下面的情况下是否应该使用方法

getStudentsWithNameStartsWithAndGradeLessThan()

@Getter 
@Setter 
@Entity 
@Table(name = "student") 
public class Student { 
  @Id 
  @GeneratedValue(strategy = GenerationType.IDENTITY) 
  @Column(name = "id", nullable = false) 
  private Long id; 
 
  @Column(name = "name") 
  private String name; 
 
  @Column(name = "average_grade") 
  private Short averageGrade; 
}

public interface StudentRepository extends JpaRepository<Student, Long> { 
  Set<Student> findByAverageGradeLessThan(Short averageGrade); 
  Set<Student> findByNameStartsWithIgnoreCase(String name); 
}

@Service 
public class StudentService { 
 
  private final StudentRepository studentRepository; 
 
  public StudentService(StudentRepository studentRepository) { 
    this.studentRepository = studentRepository; 
  } 
 
   @Transactional //(Is it required here?)
  public Set<Student> getStudentsWithNameStartsWithAndGradeLessThan(String prefix, Short averageGrade) {
 
   Set<Student> students = studentRepository.findByNameStartsWithIgnoreCase(prefix); 
   students.retainAll(studentRepository.findByAverageGradeLessThan(averageGrade)); 
    return students; 

}


}
java spring-boot spring-data-jpa
1个回答
0
投票

为了完成您对该问题的评论,我会说:

是的,

save()
方法确实已经有
@Transactional
注释,如果你打开它的实现,你可以自己看到它。

@Transactional
public <S extends T> S save(S entity) {
    Assert.notNull(entity, "Entity must not be null");
    if (this.entityInformation.isNew(entity)) {
        this.em.persist(entity);
        return entity;
    } else {
        return this.em.merge(entity);
    }
}

如果你的方法只调用它的方法而不调用其他方法,那么添加它是没有意义的。

假设你的方法有下一个主体:

    @Transactional
    public void saveEmployee(Employee employee) {
    
    repo.save(employee)
    userTrackerRepo.update() // or any other repo invocation or validation that if fails then save method should do rollback.
   }

那么有

@Transactional
注释就有意义了

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