spring - 如何使用 Spring Boot 和 JPA 在 GET 请求中获取所有一对多实体
问题描述
@GetMapping("/tutorials")
public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
try {
List<Tutorial> tutorials = new ArrayList<Tutorial>();
if (title == null)
tutorialRepository.findAll().forEach(tutorials::add);
else
tutorialRepository.findByTitleContaining(title).forEach(tutorials::add);
if (tutorials.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
我正在尝试返回所有教程,并且在每个教程中,我希望在发出 GET 请求时显示与每个教程关联的视频,但由于某种原因我无法使其正常工作。映射有什么问题吗?
package com.bezkoder.spring.datajpa.model;
import javax.persistence.*;
@Entity
@Table(name = "tutorials")
public class Tutorial {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "published")
private boolean published;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "video_id")
private List<Video> videos = new ArrayList<>();
public Tutorial() {
}
public Tutorial(String title, String description, boolean published) {
this.title = title;
this.description = description;
this.published = published;
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean isPublished) {
this.published = isPublished;
}
}
我期待一个名为视频的字段,其中包含与每个教程相关的视频实例数组,但我什么也没得到。我只得到与教程相关的字段,使一对多映射无用。
解决方案
public List<Video> getVideos() {
return videos;
}
I forgot to put a getter for videos that's why it wasn't working. Most tutorials don't show the getters and setters and assume you know that they are required in order for the mapping to work properly.
推荐阅读
- android - 如何解决此错误 Lineage 14.1 buld for morotola moto c
- php - 如何自动运行php命令行?
- php - 在codeigniter 2.0中使用rest api时总是得到“status”:false
- apache-kafka - Kafka Jdbc Connect 时间戳+自增方式
- java - Spring Boot YAML 自动数据源配置问题 - 未拾取数据源 URL
- lua - 让两个 lua 线程在同一个 lua 状态下并行运行而不并发执行是否安全?
- c# - 如何在子项目中读取 appsettings 文件的内容
- regex - 关于添加开始/结束句子标记的初学者建议:使用 Quanteda 功能与手动操作(自定义代码)
- javascript - Jquery 验证插件不适用于 addmethod
- google-apps-script - Google Apps 脚本项目触发器在共享用户中不可见