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



>我有一个问题。当我有其他实体时,我不知道如何创建 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);
}
@PostMapping
//   @Consumes(MediaType.APPLICATION_JSON_VALUE)
public Project saveProject(@RequestBody Project newProj) {
return projectService.saveProject(newProj);
}
}

当我在邮递员中执行 Get 请求时,我会收到以下输出,例如:

{
"projectId": 1,
"projectName": "jenkins",
"dgnumber": 1
}, 

我也希望收到有关门和门槛的信息。我不明白如何更准确地做这件事。

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

@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;

默认情况下,与@ManyToMany关联的数据是延迟加载的。您需要指定要急切加载的内容(如果您使用的是 spring-data,则可以使用实体图(。

有关详细信息,请参阅链接:Spring Data JPA 和命名实体图

相关内容

  • 没有找到相关文章

最新更新