Spring事务:如果我在方法上不使用@Transaction注解会发生什么?

16

我正在使用Spring Boot、Spring Rest Controller和Spring Data JPA。如果我不指定@Transaction,那么记录仍将被创建,但我想了解它是如何发生的。我的理解是,Spring默认添加具有默认参数的事务,但不确定它是在Service层还是Repository中添加。

 public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
 }

 @Service
 public class CustomerServiceImpl implements CustomerService> {

   List<Customer> findByLastName(String lastName){
     //read operation
    }

 // What will happen if @Transaction is missing. How record get's created without the annotation
  public Customer insert(Customer customer){
  // insert operations
   }
 }

投了一票,因为我有同样的问题,并花了很长时间才找到答案。 - Bằng Rikimaru
在我看来,Spring 不应该添加任何 tx 行为。传统的 RDBMS 会提供“自动提交”执行模式,在这种模式下,每个 SQL 语句都在其自己独立的事务中执行。 - Victor Sorokin
2个回答

6

Spring Data JPA 在 Repository 层中的 SimpleJpaRepository 类中添加了 @Transactional 注解。这是所有 Spring Data JPA 存储库所扩展的基本 Repository 类。

例如:

/*
     * (non-Javadoc)
     * @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
     */
    @Transactional
    public <S extends T> S save(S entity) {

        if (entityInformation.isNew(entity)) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
    }

3
尽管Spring会自动在DAO层添加@Transactional注释,但这不是正确的位置或行为。该注释必须位于服务层,这里有一个已经回答的问题(链接)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接