首页 > 解决方案 > Spring Boot + Kotlin 中的 NamedNativeQuery / ConstructorResult:找不到 PersistentEntity

问题描述

我正在尝试添加一个查询方法来AlertRepository使用 NamedNativeQuery / ConstructorResult。我们的 Kotlin 代码很大程度上基于这个 Java 示例:https ://github.com/spring-projects/spring-data-examples/tree/master/jpa/jpa21#support-for-custom-sqlresultsetmapping-with-constructorresult

这是我添加到Alert实体中的内容:

@SqlResultSetMapping(name = "hourly-alert-counts",
        classes = [
            ConstructorResult(targetClass = HourlyAlertCount::class, columns = [
                ColumnResult(name = "day", type = Int::class),
                ColumnResult(name = "hour", type = Int::class),
                ColumnResult(name = "count", type = Long::class)
            ])
        ]
)
@NamedNativeQuery(
        name = "Alert.getHourlyCountsByConfigurationItemId",
        query = "select {fn DAYOFWEEK(reported_time)} as day, hour(reported_time) as hour, count(*) as count from alert\n" +
                "where configuration_item = ?1 group by configuration_item, {fn DAYOFWEEK(reported_time)}, hour(reported_time)",
        resultSetMapping = "hourly-alert-counts"
)
data class Alert(
  ...

并到 AlertRepository:

@Query(nativeQuery = true)
fun getHourlyCountsByConfigurationItemId(id: Long): List<HourlyAlertCount>

最后,HourlyAlertCount POJO:

data class HourlyAlertCount(
    val day: Int,
    val hour: Int,
    val count: Long
)

当我到达此端点时,我收到以下错误:

{"cause":null,"message":"Couldn't find PersistentEntity for type class xxx.HourlyAlertCount!"}

ConstructorResult / ColumnResult 应该是 Java 中的注解,但是如果我们在它们前面添加“@”,我们的 Kotlin 代码将无法编译;这篇博文建议忽略“@”。我们使用的是 spring-data-jpa 2.09 和 Hibernate 5.2.17。

标签: javaspring-bootkotlin

解决方案


推荐阅读