You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring构建REST服务时无法导入javax.persistence相关包求助

问题:Spring REST服务搭建时无法导入javax.persistence相关注解包

问题详情

我正在按照《使用Spring构建REST服务》指南逐步操作,搭建REST服务器的第一步就卡壳了——没法导入@Entity注解需要的javax相关包。

实体类代码

package payroll;

import java.util.Objects;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
class Employee {

    private @Id @GeneratedValue Long id;
    private String name;
    private String role;

    Employee() {}

    Employee(String name, String role) {
        this.name = name;
        this.role = role;
    }

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public String getRole() {
        return this.role;
    }

    public void setId(Long id) {
        this.id = id;
    }

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

    public void setRole(String role) {
        this.role = role;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (!(o instanceof Employee))
            return false;
        Employee employee = (Employee) o;
        return Objects.equals(this.id, employee.id) && Objects.equals(this.name, employee.name)
                && Objects.equals(this.role, employee.role);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.id, this.name, this.role);
    }

    @Override
    public String toString() {
        return "Employee{" + "id=" + this.id + ", name='" + this.name + '\'' + ", role='" + this.role + '\'' + '}';
    }
}

解决方案

1. 补充JPA相关依赖

问题核心是缺少JPA相关依赖,根据你用的构建工具添加对应配置:

Maven(pom.xml)

添加Spring Data JPA starter依赖,它会自动引入JPA规范和默认实现:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Gradle(build.gradle)

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

2. 适配Spring Boot 3.x版本规则

如果你的Spring Boot是3.x及以上版本,javax.persistence已经被迁移到Jakarta EE规范,需要把导入路径改成:

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;

starter依赖会自动适配Jakarta版本,无需额外调整。

3. 刷新依赖并重构

添加依赖后,执行构建工具的刷新操作:

  • Maven:运行mvn clean install或者在IDE里点击Maven刷新按钮
  • Gradle:运行gradle build或者在IDE里点击Gradle刷新按钮
    之后重启IDE的代码检查,导入问题就能解决。

内容的提问来源于stack exchange,提问作者orangezx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 08:35:33