我有问题。当我有其他实体时,我不知道如何创建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;
这是Gate实体
@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);
}
@PostMapping
// @Consumes(MediaType.APPLICATION_JSON_VALUE)
public Project saveProject(@RequestBody Project newProj) {
return projectService.saveProject(newProj);
}
}
在邮递员中执行Get请求时,例如,收到以下输出:
{
"projectId": 1,
"projectName": "jenkins",
"dgnumber": 1
},
我希望也能收到有关门和阈值的信息。我不明白该怎么做。
答案 0 :(得分:1)
相关实体未加载到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;
答案 1 :(得分:0)
默认情况下,与@ManyToMany
关联的数据是延迟加载的。您需要指定您希望加载的内容(如果您使用的是spring-data,则可以使用实体图)。
请查看链接以获取详细信息:Spring Data JPA And NamedEntityGraphs