1

默认情况下,用户定义的存储库方法是只读的,修改查询被 @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 覆盖 save :

@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 时保存方法的工作原理:

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

    }
}
4

1 回答 1

0

看看 SimpleJpaRepository。

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

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

为什么你认为 save 不是事务性的?

于 2018-10-23T14:36:03.060 回答