首页 > 解决方案 > 如何使用 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;
    }
}

我期待一个名为视频的字段,其中包含与每个教程相关的视频实例数组,但我什么也没得到。我只得到与教程相关的字段,使一对多映射无用。

标签: springjpa

解决方案


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.


推荐阅读