JPA Repository的findLast方法返回NonUniqueResultException异常?

huangapple go评论70阅读模式
英文:

JPA Repository - findLast returning NonUniqueResultException?

问题

我有一个类似这样的 JpaRepository 函数:

fun findLastByOrganisationAndFileType(organisation: Organisation, fileType: FileType) : OrganisationFile?

但出现了一个问题,当我为一个组织有两个相同类型的文件时,我收到以下错误:

>javax.persistence.NonUniqueResultException: 查询未返回唯一结果:2

我知道这不是唯一的,但我不知道为什么它需要是唯一的,毕竟它是使用的 findLast,而不是 find

它需要指定一个排序(order by)吗?

英文:

I have a JpaRepository function that looks like this:

fun findLastByOrganisationAndFileType(organisation: Organisation, fileType: FileType) : OrganisationFile?

For some reason though, when I have 2 files of the same type for an organisation, I receive the following error:

>javax.persistence.NonUniqueResultException: query did not return a unique result: 2

I know it's not unique, but I don't know why it needs to be, afterall it's using findLast, rather than find.

Does it need an order by to be specified?

答案1

得分: 2

就像在 SQL 中调用没有排序的 limit 或等效操作一样,在没有排序的情况下调用 limit 没有太多意义(除了获取数据样本)。在这里,你也需要指定方法名的 OrderBy 部分:

fun findLastByOrganisationAndFileTypeOrderBySomeField(organisation: Organisation, fileType: FileType) : OrganisationFile?
英文:

Just like in SQL calling limit or equivalent without an ordering does not make much sense without ordering (other than getting a sample of data), here you also need to specify OrderBy part of the method name:

fun findLastByOrganisationAndFileTypeOrderBySomeField(organisation: Organisation, fileType: FileType) : OrganisationFile?

huangapple
  • 本文由 发表于 2020年10月22日 15:51:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64477648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定