Spring Boot应用程序中的NonUniqueResultException

时间:2019-06-18 08:57:57

标签: spring spring-boot jpa kotlin

在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

我要去哪里错了?

1 个答案:

答案 0 :(得分:1)

命名您的方法

findAllColors() 

告诉Spring Data返回类型是collection。

我找不到任何文档,但是关于这个主题的博客文章说:

  
      
  1. 能够按名称和(原始)参数类型查找方法。
  2.   
  3. 名为…All(...)的方法影响项目的集合和/或返回集合。
  4.   
  5. 带有标识符的方法称为…ById(…)。 4让我们删除ID,以扩展“可序列化”要求。
  6.   

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