hibernatespring-bootspring-data-jpaspring-repositories

Spring JPA no @Transnational on save JpaRepository


by default user defined repository methods are read only , modifying queries are overridden by @Transactional , sample from SimpleJpaRepository from spring :

@Repository
@Transactional(readOnly = true)
public class SimpleJpaRepository<T, ID> implements JpaRepository<T, ID>, JpaSpecificationExecutor<T> {

 */
@Transactional
public <S extends T> S save(S entity) {

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

I noticed JpaRepository doesn't override save with @Transactional :

@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {

the save method is inside CrudRepository ( no transnational here )

/**
 * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
 * entity instance completely.
 * 
 * @param entity must not be {@literal null}.
 * @return the saved entity will never be {@literal null}.
 */
<S extends T> S save(S entity);

so how the save method is working when extending JpaRepository without @Transnational example :

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

no transactional here

@Override
public void test() {
    {
        User user=new User();
        user.setName("hello");
        user.setLastName("hello");
        user.setActive(1);
        user.setPassword("hello");
        user.setEmail("hello@hello.com");
        userRepository.save(user);

    }
}

Solution

  • Have a look at SimpleJpaRepository.

    https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/repository/support/SimpleJpaRepository.java

    This is the default repository implementation and is shows how @Transactional is used also in the generated classes from your Repository interfaces.

    Why do you think that save is not transactional?