我有个问题。当我有其他实体时,我不知道如何创建 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;
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
与 a 关联的数据@ManyToMany
默认是延迟加载的。您需要在急切加载中指定您想要的(如果您使用的是 spring-data,则可以使用实体图)。
添加回答
举报
0/150
提交
取消