Spring Data JPA流查询方法导致有关事务的异常 [英] Spring Data JPA streaming query methods cause an exception about transactions
问题描述
如果我使用返回Stream
的Spring Data存储库方法,则总是会收到以下异常:
If I use a Spring Data repository methods that returns a Stream
, I always get the following exception:
org.springframework.dao.InvalidDataAccessApiUsageException: You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction.
org.springframework.data.jpa.repository.query.JpaQueryExecution$StreamExecution.doExecute(JpaQueryExecution.java:338)
org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
com.sun.proxy.$Proxy201.findByPodcast(Unknown Source)
<my controller class>$$Lambda$118/2013513791.apply(Unknown Source)
有问题的代码确实应该在事务中执行.我有:
The code in question really ought to be executing in a transaction, however. I have:
- 使用了
OpenSessionManagerInViewFilter
- 启用声明式事务管理(在我的根上下文配置中为
@EnableTransactionManagement
),并由控制器类和进行注释,并使用@Transactional
- Used the
OpenSessionManagerInViewFilter
- Enabled declarative transaction management (
@EnableTransactionManagement
in my root context configuration) and annotated by the controller class and the request method with@Transactional
我还尝试将代码包装在TransactionTemplate
中,并将结果收集在List
中,以避免事务超出范围,但这仍然没有用.控制器方法:
I've also tried wrapping the code in a TransactionTemplate
and collecting the results in a List
to avoid the transaction going out of scope, but that still hasn't worked. Controller methods:
@RequestMapping ( "/pod/{id}" )
@Transactional
public Stream<RSSPodcastItem> podItems (@PathVariable("id") UUID id)
{
return pods.get (id).map (items::findByPodcast).orElseThrow (() -> new RuntimeException ("failed"));
}
@RequestMapping ( "/podlist/{id}" )
@Transactional
public List<RSSPodcastItem> podItemsList (@PathVariable("id") UUID id)
{
return tt.execute (ts ->
pods.get (id).map (items::findByPodcast).orElseThrow (() -> new RuntimeException ("failed"))
.collect (Collectors.toList()));
}
上下文根配置类:
@Configuration
@ComponentScan ( ... my package names ...)
@EnableTransactionManagement
@EnableJpaRepositories( ... package with repositories ...)
public class SharedConfig
{
@Bean
public DataSource dataSource ()
{
// .... snipped
}
@Bean
EntityManagerFactory entityManagerFactory ()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean ();
entityManagerFactoryBean.setDataSource (dataSource());
entityManagerFactoryBean.setJpaVendorAdapter (new HibernateJpaVendorAdapter ());
entityManagerFactoryBean.setPackagesToScan ( ... package with entities ...);
entityManagerFactoryBean.setJpaPropertyMap (hibernateProperties());
entityManagerFactoryBean.afterPropertiesSet ();
return entityManagerFactoryBean.getObject ();
}
@Bean
JpaTransactionManager transactionManager ()
{
JpaTransactionManager transactionManager = new JpaTransactionManager ();
transactionManager.setEntityManagerFactory (entityManagerFactory());
return transactionManager;
}
@Bean
TransactionTemplate transactionTemplate (JpaTransactionManager tm)
{
return new TransactionTemplate (tm);
}
@Bean
Map<String, ?> hibernateProperties ()
{
Map<String, Object> m = new HashMap<> ();
m.put ("hibernate.dialect", MySQL5Dialect.class);
m.put ("hibernate.dialect.storage_engine", "innodb");
boolean devSystem = isDevSystem ();
m.put ("hibernate.hbm2ddl.auto", devSystem ? "update" : "create-only"); // will need to handle updates by hand on live system, but creation is OK.
m.put ("hibernate.show_sql", "" + devSystem);
m.put ("hibernate.cache.use_second_level_cache", "" + !devSystem);
return m;
}
有什么建议吗?
推荐答案
根据
存储库客户端可以...在try-with-resources块中使用方法调用的结果.
Repository clients can ... use the result of the method call in a try-with-resources block. 和Spring Data 参考: And Spring Data reference: Stream可能包装了特定于数据存储的基础资源,因此必须在使用后关闭.您可以使用close()方法或使用Java 7 try-with-resources块来手动关闭Stream. A Stream potentially wraps underlying data store specific resources and must therefore be closed after usage. You can either manually close the Stream using the close() method or by using a Java 7 try-with-resources block. 因此,我认为您应该将流包装到try-with-resource块中,并作为例外建议设置只读事务,如下所示: So I think you should wrap your stream to try-with-resource block and, as exception suggest, set read-only transaction, something like this: 其他信息: Spring数据-Java 8示例 这篇关于Spring Data JPA流查询方法导致有关事务的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
@RequestMapping("/pod/{id}")
@Transactional(readOnly = true)
public Stream<RSSPodcastItem> podItems (@PathVariable("id") UUID id) {
try (Stream<RSSPodcastItem> items = repository.findByPodcast(...)) {
return items...;
}
}