【问题标题】:Can't get existByProperty to run: "No property student found for type Student!"无法让 existsByProperty 运行:“没有找到学生类型的属性学生!”
【发布时间】:2020-04-06 13:29:17
【问题描述】:

我正在尝试编写“existsBy”查询,但无法使其工作。我知道JpaRepository 中有一个existByID,但我需要通过属性student_id 进行检查。我尝试了无数种写函数名的方法,但我似乎无法正确。

public class Student implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private long student_id;

+other fields and getters and setters...
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
    boolean existsByStudentid(Long student_id);
}

错误:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property student found for type Student!

【问题讨论】:

    标签: mysql spring spring-boot jpa


    【解决方案1】:

    Spring Data 使用下划线作为保留字符。我认为不可能以这种方式使用它。我认为没有其他选项可以重命名变量。

    https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

    所以字段必须按照以下约定命名

    private long studentId;
    

    (下划线可用于遍历嵌套属性:要解决这种歧义,您可以在方法名称中使用 _ 手动定义遍历点。)

    【讨论】:

    • 是的,感谢您的解释。不幸的是,我们项目的前端和后端都有太多代码现在无法更改,尽管我们可能不得不这样做。但是我仍然可以在自定义查询中使用 student_id 还是不会运行?
    • 不,我认为它可以在自定义查询中使用。因为我也在我的数据库中使用下划线而不是驼峰表示法。例如: SELECT student_id FROM STUDENT 应该可以工作。
    • 我更具体地考虑了 JpaRepository 中的 @Query 注释,我将如何在属性中使用下划线编写查询?
    【解决方案2】:

    您的住宿名称是 student_id

    所以查询方法应该是

    @Repository
    public interface StudentRepository extends JpaRepository<Student, Long> {
        boolean existsByStudent_id(Long student_id);
    }
    

    顺便说一句:属性名称中的 _ 不是 Java 中推荐的常量样式

    【讨论】:

    • 同样的错误:原因:org.springframework.data.mapping.PropertyReferenceException:没有找到学生类型的属性学生!我知道我不应该使用 student_id,但我正在尝试使用 RabbitMQ 从另一个数据库同步表,而 student_id 是 PK。我不知道为什么叫它。这是一篇学士论文,其他小组成员之一说这是常态,所以我就照做了。但是,是的,使用 existsByStudent_id 仍然出错
    • @SimonMartinelli 这也行不通,他们需要使用正确的命名约定,因为 spring 会做出假设。 existsByStudent_id,将在当前学生对象中查找 Student 对象,然后在其中查找 id 字段。
    • 谢谢,但我仍然可以在自定义查询中使用 student_id 还是不会运行?
    猜你喜欢
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多