Spring JPA no @Transnational保存JpaRepository

时间:2018-10-23 13:53:26

标签: hibernate spring-boot spring-data-jpa spring-repositories

默认情况下,用户定义的存储库方法为只读,修改查询被@Transactional覆盖,Spring的SimpleJpaRepository示例:

@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);
    }
}

我注意到JpaRepository不会使用@Transactional覆盖保存:

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

保存方法位于CrudRepository内部(此处没有跨国语言)

/**
 * 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);

所以在不使用@Transnational示例的情况下扩展JpaRepository时,save方法的工作方式:

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

此处无交易

@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);

    }
}

1 个答案:

答案 0 :(得分:0)

看看SimpleJpaRepository。

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

这是默认的存储库实现,它显示了如何从存储库接口生成的类中也使用@Transactional。

您为什么认为保存不是事务性的?