挑战:
我正在尝试从我的数据库中批量获取嵌套实体的集合。生成的数据集包含数千个实体,因此我的方法是根据这篇文章以分页方式获取实体。数据是从基于 Web 的前端获取的,纯非分页查询最多需要 10 秒(不可接受)。
问题:
“父”实体已正确获取,但“子”实体似乎未获取。在来自 TestRepository.getRankedTests(...) 的结果实体列表中,“子”实体列表未初始化,访问它们将导致LazyInitializationException
. 这指向我的问题的方向SqlResultMapping
,但我看不到错误。我试图SqlResultMapping
为孩子注入错误,这会导致休眠在运行时抱怨,所以它似乎试图将我的配置映射到子实体的属性,尽管未初始化的子实体集合让我哑口无言。
父实体(Test.kt):
@NamedNativeQuery(
name = "Test.getRankedTests",
query = """
select *
from (
select
*,
DENSE_RANK() over (
order by "o.id"
) rank
from (
select
o.id as "o.id",
o.version as "o.version",
a.id as "a.id",
a.organisation_id as "a.organisation_id",
a.type as "a.type"
from organisation o
left join address a on o.id = a.organisation_id
order by o.organisation_number
) o_a_an_c
) o_a_an_c_r
where o_a_an_c_r.rank > :min and o_a_an_c_r.rank <= :max
""",
resultSetMapping = "TestMapping"
)
@SqlResultSetMapping(
name = "TestMapping",
entities = [
EntityResult(
entityClass = Test::class,
fields = [
FieldResult(name = "id", column = "o.id"),
FieldResult(name = "version", column = "o.version"),
]
),
EntityResult(
entityClass = TestChild::class,
fields = [
FieldResult(name = "id", column = "a.id"),
FieldResult(name = "organisation", column = "a.organisation_id"),
]
),
]
)
@Entity
@Table(name = "organisation")
class Test(
@Id
val id: Long,
val version: Long,
@OneToMany(mappedBy = "organisation", cascade = [CascadeType.ALL], orphanRemoval = true)
val addresses: List<TestChild>,
)
子实体(TestChild.kt):
@Entity
@Table(name = "address")
@Suppress("LongParameterList")
class TestChild(
@Id
val id: Long,
@ManyToOne(fetch = FetchType.LAZY)
val organisation: Test,
)
存储库(TestRepository.kt):
@Repository
interface TestRepository : JpaRepository<Test, Long> {
fun getRankedTests(
min: Long,
max: Long
): List<Test>
}