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