【发布时间】:2020-08-01 11:28:58
【问题描述】:
我需要根据名为owner 的列的值从数据库中检索Category 的列表。这是我的Category -
@Entity
@Table(name = "categories")
class Category(@Column(name = "category_id", nullable = false)
@Id @GeneratedValue(strategyGenerationType.AUTO)
var id: Long = 0,
@Column(name = "category_owner", nullable = false)
@field:NotNull(message = "Please assign an owner")
var owner: Long?,
@Column(name = "category_name", nullable = false)
@field:NotEmpty(message = "Please assign a name")
var name: String?)
这是我定义函数findByOwner的界面-
interface CategoryRepository: JpaRepository<Category, Long> {
fun findByOwner(categoryOwner: Long): List<Category>
}
但是,当我调用该方法时,我没有得到任何响应。我已确保数据库具有正确的数据,并且我提供了正确的所有者 ID。甚至使缓存等无效。可能出了什么问题?
编辑:
spring.jpa.show-sql=true之后-
findAll()
Hibernate: select category0_.category_id as category1_0_, category0_.category_name as category2_0_, category0_.category_owner as category3_0_ from categories category0_
findByOwner()
Hibernate: select category0_.category_id as category1_0_, category0_.category_name as category2_0_, category0_.category_owner as category3_0_ from categories category0_ where category0_.category_owner=?
编辑 2:
事实证明,我的实现一直都很好。该错误在我的service 中。
【问题讨论】:
-
你能做一个
findAll()并检查它是否正在返回数据并且至少一条返回的记录包含你在上述查询中使用的owner值吗? -
findAll()按预期工作。 -
这是个好消息,排除了任何基本错误。现在您可以将
spring.jpa.show-sql=true添加到您的application.properties并告诉我为findAll生成了哪些查询以及为findByOwner()生成了哪些查询。您可以用结果更新问题,因为很难用结果发表评论 -
完成。我可以看到
findByOwner()中的 ownerId 不存在。 -
我的想法已经用完了。除了
where条件和where条件`对于第二个查询是正确的之外,两个查询都是相同的
标签: spring spring-boot spring-data-jpa spring-data