【发布时间】:2019-01-26 02:28:08
【问题描述】:
我试图理解为什么这段代码不起作用
在组件中:
@PostConstruct
public void runAtStart(){
testStream();
}
@Transactional(readOnly = true)
public void testStream(){
try(Stream<Person> top10ByFirstName = personRepository.findTop10ByFirstName("Tom")){
top10ByFirstName.forEach(System.out::println);
}
}
和存储库:
public interface PersonRepository extends JpaRepository<Person, Long> {
Stream<Person> findTop10ByFirstName(String firstName);
}
我明白了:
org.springframework.dao.InvalidDataAccessApiUsageException:您正在尝试执行流式查询方法,而无需围绕事务保持连接打开,以便可以实际使用 Stream。确保使用流的代码使用@Transactional 或任何其他声明(只读)事务的方式。
【问题讨论】:
-
@Transactional需要 Spring AOP。默认的 Spring AOP 实现使用标准的 JDK 代理,它不适用于类内调用。这在official documentation 中有非常详细的说明。如果您需要在同一个类中使用 AOP 语义,请考虑使用 AspectJ 代理。