【问题标题】:NonUniqueResultException in Spring Boot applicationSpring Boot 应用程序中的 NonUniqueResultException
【发布时间】:2019-06-18 08:57:57
【问题描述】:

在 Spring Boot / Kotlin 应用程序中,我有这个存储库:

interface CatRepository : CrudRepository<Cat, Long> {

    @Query(value = "SELECT DISTINCT c.color FROM cat c", nativeQuery = true)
    fun findColors(): List<String>
}

然后在我的控制器中我有这个:

@Controller
class HtmlController(private val repository: CatRepository) {

    @GetMapping("/")
    fun index(model: Model): String {
        model["colors"] = repository.findColors()
        return "index"
    }

}

然后在我的模板中我有这个:

<select name="color">
    {{#colors}}
        <option value="">{{.}}</option>
    {{/colors}}
</select>

当数据库的cat 表中只有一个cat 时,这是可行的。当我添加另一个时,我收到此错误:

NonUniqueResultException:查询未返回唯一结果:2

我哪里出错了?

【问题讨论】:

  • 能否设置 logging.level.org.hibernate.SQL=debug 并发布生成的 SQL 语句?
  • @SimonMartinelli 是的。它记录了我在注释中的确切查询。
  • 这只是一个猜测,但你能命名你的方法 findAllColors()
  • 一个很好的猜测!如果您写了答案,我会正确标记(说明原因的加分...)
  • 完成。感谢您接受我的回答。我很乐意提供帮助

标签: spring spring-boot jpa kotlin


【解决方案1】:

命名你的方法

findAllColors() 

告诉 Spring Data 返回类型是集合。

我找不到任何文档,但有一篇关于此主题的博客文章说:

  1. 能够按名称和(原始)参数类型查找方法。
  2. 名为 …All(…) 的方法会影响项目集合和/或返回集合。
  3. 采用标识符的方法被命名为…ById(…)。 4 让我们放弃 ID extends Serializable 要求。

来源:https://spring.io/blog/2017/06/20/a-preview-on-spring-data-kay#improved-naming-for-crud-repository-methods

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2017-12-30
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    相关资源
    最近更新 更多