Spring Transaction:如果我不在方法上给出@Transaction注释会发生什么

JDe*_*Dev 6 java spring jpa transactions spring-mvc

我正在使用Spring-Boot,Spring Rest Controller和Spring Data JPA.如果我没有指定@Transaction,那么也记录get的创建,但我想了解它是如何发生的.我的理解是Spring默认添加一个带有默认参数的事务但不确定它添加的位置是添加Service层还是存储库.

 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
   }
 }
Run Code Online (Sandbox Code Playgroud)

eke*_*iga 5

Spring Data JPA 在 Repository 层添加了 @Transactional 注释,特别是在 SimpleJpaRepository 类中。这是为所有 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)