首页 > 解决方案 > Spring 的 findByColumnName 返回空列表

问题描述

我需要Category根据名为 的列的值从数据库中检索一个列表owner。这是我的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.

标签: springspring-bootspring-data-jpaspring-data

解决方案


根据列的名称创建您的命名方法。

fun findByCategoryOwner(categoryOwner: Long): List<Category>

或者使用@Query

@Query("SELECT * FROM categories WHERE category_owner = ?1", nativeQuery = true)
fun findByOwner(cateogryOwner: Long): List<Category

推荐阅读