在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
我要去哪里错了?
答案 0 :(得分:1)
命名您的方法
findAllColors()
告诉Spring Data返回类型是collection。
我找不到任何文档,但是关于这个主题的博客文章说:
- 能够按名称和(原始)参数类型查找方法。
- 名为…All(...)的方法影响项目的集合和/或返回集合。
- 带有标识符的方法称为…ById(…)。 4让我们删除ID,以扩展“可序列化”要求。