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
相关产品推荐
相关产品推荐

