16

I am using Spring-Boot, Spring Rest Controller and Spring Data JPA. If I don't specify @Transaction then also record get's created but I will like to understand how it happens.My understanding is that Spring by default adds a transaction with default parameters but not sure where it adds is it add Service layer or at 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
   }
 }
JDev
  • 1,662
  • 4
  • 25
  • 55
  • voted because I have same question and take a long time to find the answer. – Bằng Rikimaru Jun 08 '17 at 10:04
  • Imho, Spring shouldn't add any tx behavior. What you'll get with traditional RDBMS is 'auto-commit' execution mode, where each SQL statement executing in its own separate transaction. – Victor Sorokin Feb 27 '19 at 16:31

2 Answers2

6

Spring Data JPA adds the @Transactional annotation at the Repository layer specifically in the class SimpleJpaRepository.This is the base Repository class which is extended for all Spring Data JPA repositories

e.g

/*
     * (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);
        }
    }
ekem chitsiga
  • 5,523
  • 2
  • 17
  • 18
3

Although Spring add automatically the @Transactional annotation at DAO layer, it is not the correct place nor correct behavior. The annotation must be located at service layer, there is an answered question here.

Community
  • 1
  • 1
n3k0
  • 577
  • 14
  • 40