【发布时间】:2022-01-01 01:46:45
【问题描述】:
我正在尝试在我的 Kotlin 项目中使用 JPA Streams,但我不断收到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.
我知道使用 Streams 的先决条件,并且我已经用 @Transactional 包围了我的代码并关闭了 Stream 但它不起作用。
这是我的代码:
@Repository
interface MyRepository : JpaRepository<SomeValue, Long> {
@QueryHints(value = [
QueryHint(name = HINT_FETCH_SIZE, value = "100"),
QueryHint(name = HINT_CACHEABLE, value = "false"),
QueryHint(name = READ_ONLY, value = "true")
])
@Query(
"""select s.id, s.name
from Some s
""",
nativeQuery = true
)
fun findSomeValues(
): Stream<SomeValue>
}
@Service
class Someservice(
private val myRepository: MyRepository,
...
) {
@Transactional(readOnly = true)
fun retrieveSomeValues(
): SomeDto {
val someDto =
myRepository.findSomeValues().use {
it.map { SomeObject(it.id, it.name) }
....
}
return someDto
}
}
编辑:
相关依赖:
Spring Boot: 2.3.4.RELEASE
Kotlin: 1.3.72
Spring-boot-starter-data-jpa
【问题讨论】:
-
@Transactional仅在类和方法为public且非 final 时才有效。 -
类和方法都是公共的,不是最终的。
-
我问是因为代码没有使用
open关键字。 -
我使用的是
org.jetbrains.kotlin.plugin.spring,所以它应该在编译时打开所有类。
标签: spring-boot kotlin spring-data-jpa java-stream