为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 JPA 关系实体创建 RestAPI

如何使用 JPA 关系实体创建 RestAPI

白衣非少年 2021-10-13 13:38:01
我有个问题。当我有其他实体时,我不知道如何创建 API。我与 Postman 合作,当我请求查看数据库中的所有项目时,我也想接收实体。例如,这是我的实体:@Entity@Table(name = "project")public class Project {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "proj_id")    private int projectId;    @Column(name = "project_name")    private String projectName;    @Column(name = "dg_number")    private int dgNumber;    @ManyToMany    @JoinTable(name = "project_gate_relation", joinColumns = @JoinColumn(name = "proj_id"), inverseJoinColumns = @JoinColumn(name = "gate_id"))    @JsonBackReference    private  List<Gate> gates;    @ManyToMany    @JoinTable(name = "project_threshold_relation", joinColumns = @JoinColumn(name = "proj_id"), inverseJoinColumns = @JoinColumn(name = "thresholdgates_id"))    @JsonBackReference    private  List<Threshold> thresholds;这是门实体@Entity@Table(name = "gate")public class Gate {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "gate_id")    private int gateId;    @Column(name = "gate_type")    private String gateType;    @Column(name = "gate_value")    private float value;阈值实体@Entity@Table(name = "threshold")public class Threshold {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "threshold_id")    private int thresholdId;    @Column(name = "threshold_value")    private int thresholdValue;    @Column(name = "threshold_type")    private String thresholdType;控制器@RestController@RequestMapping(ProjectController.PROJECT_URL)public class ProjectController {    public static final String PROJECT_URL = "/cidashboard/projects";    @Autowired    private final ProjectService projectService;    public ProjectController(ProjectService projectService) {        this.projectService = projectService;    }    @GetMapping    public List<Project> getAllProjects(){        return projectService.findAllProjects();    }    @GetMapping("/{id}")    public Project getProjectById(@PathVariable int id) {        return projectService.findProjectById(id);    }
查看完整描述

2 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

JPA 中默认不加载相关实体。你必须在@ManyToMany 关系中定义fetch = FetchType.EAGER


@ManyToMany(fetch = FetchType.EAGER)

@JoinTable(name = "project_gate_relation", joinColumns = @JoinColumn(name = "proj_id"), inverseJoinColumns = @JoinColumn(name = "gate_id"))

@JsonBackReference

private  List<Gate> gates;


@ManyToMany(fetch = FetchType.EAGER)

@JoinTable(name = "project_threshold_relation", joinColumns = @JoinColumn(name = "proj_id"), inverseJoinColumns = @JoinColumn(name = "thresholdgates_id"))

@JsonBackReference

private  List<Threshold> thresholds;


查看完整回答
反对 回复 2021-10-13
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

与 a 关联的数据@ManyToMany默认是延迟加载的。您需要在急切加载中指定您想要的(如果您使用的是 spring-data,则可以使用实体图)。


查看完整回答
反对 回复 2021-10-13
  • 2 回答
  • 0 关注
  • 139 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信