java PropertyReferenceException:按project_id排序时找不到类型“Project”的属性“project "

mfpqipee  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(169)

在My SpringBoot/JPA(Postgres)项目中,
我有一个项目表,定义为:

create table projects(
 project_id int primary key,
 name varchar(255),
 description text
);

字符串
在我的控制器中,我有一个获取项目列表的方法:

@GetMapping("/list")
@ResponseBody
public Page<Project> list(@AuthenticationPrincipal UserDetails currentUserDetails) {
    int page = 0;
    int size = 100;
    Sort sort = Sort.by("name").ascending();
    PageRequest p = PageRequest.of(page, size, sort);

    return projectService.list(p);
}


这一切都很好。当我将这段代码改为按project_id列排序时,问题出现了:

Sort sort = Sort.by("project_id").ascending();


现在,我得到了以下异常:
2024-01-01T14:34:04,424 ERROR [http-nio-8081-exec-6] o.a.j.l.DirectJDKLog:Servlet.service()for servlet [dispatcherServlet] in context with path [] throughed exception [Request processing failed:org.springframework.data.mapping.PropertyReferenceException:No property 'project' found for type 'Project'] with root cause org.springframework.data.mapping.PropertyReferenceException:在org. springframework. data. mapping. PropertyPath中找不到类型“Project”的属性“project”。(PropertyPath.java:90)
我的Project实体类非常简单:

@Entity
@Table(name = "Projects")
public class Project {
@Id
@GeneratedValue(generator = "ProjectSeq")
@SequenceGenerator(name = "ProjectSeq", sequenceName = "PROJECTS_PROJECT_ID_SEQ", allocationSize = 1)
Integer project_id;
String name;

public Integer getProject_id() {
    return project_id;
}

public void setProject_id(Integer project_id) {
    this.project_id = project_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

String description;
}


我是不是陷入了一个保留字的境地?

wgx48brx

wgx48brx1#

这里的问题是由于在构建PropertyPath示例时,下划线被解释为下划线。此时,您的project_id将被拆分为project + id
要修复它,您可以更改实体类以使用camelCase属性。像这样:

@Column(name = "project_id")
    Integer projectId;
    public Integer getProjectId() {
        return projectId;
    }
    public void setProjectId(Integer projectId) {
        this.projectId = projectId;
    }

字符串
使用@Column注解,您将获得未更改的数据库列名,但Java名称将在camelCase中-建议用于属性。

h7wcgrx3

h7wcgrx32#

下划线被视为Spring Data JPA文档中提到的保留字符:
由于我们将下划线字符视为保留字符,因此强烈建议遵循标准Java命名约定(即,在属性名中不使用下划线,而是使用驼峰大小写)。
您应该将project_id属性更改为projectId。它不需要对数据库进行任何更改,因为默认情况下会完成从camel case到snake case的转换。

相关问题