Spring Data JPA一对多POST映射问题

如何解决Spring Data JPA一对多POST映射问题

我正在尝试为视频库开发REST API。 使用电影控制器,我想获取,发布,放置和删除电影实体 (具有ID(已生成类型标识,并且是主键),标题,类型,费率和库存编号的列

“流派”是另一种实体,因为一部电影可能是唯一的流派(在我的项目中)

我希望我的api接受以下JSON请求

{
  "title":"John Wick","rate":8.2,"numberInStock":19,"genreId":2
}

so genreId指向ID类型表,并指向ID为2的类型名称,即“动作”

当我尝试发布以下电影时,邮递员出现415错误

{
    "timestamp": "2020-08-11T03:57:31.792+00:00","status": 415,"error": "Unsupported Media Type","message": "","path": "/video-library/movies/"
}

有人,请指导我做错了地方

Movie.java

@Entity
@Table
public class Movie {
    
  @Id
  @GeneratedValue (strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Integer id;
  private String title;
  private int rate;
  
  @Column(name = "numberInStock")
  private int numberInStock;
  
  
  @ManyToOne(targetEntity = Genre.class)
  @JoinColumn(name="genreId")
  private Genre genre;

  public Movie() {

  }

public Movie(Integer id,String title,int rate,int numberInStock,Genre genre) {
    super();
    this.id = id;
    this.title = title;
    this.rate = rate;
    this.numberInStock = numberInStock;
    this.genre = genre;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getRate() {
    return rate;
}

public void setRate(int rate) {
    this.rate = rate;
}

public int getNumberInStock() {
    return numberInStock;
}

public void setNumberInStock(int numberInStock) {
    this.numberInStock = numberInStock;
}

@JsonManagedReference 
public Genre getGenre() {
    return genre;
}

public void setGenre(Genre genre) {
    this.genre = genre;
}


}

Genre.java

@Entity
@Table
public class Genre {

@Id
@Column(name="genreId")
@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

@OneToMany(mappedBy="genre",cascade = CascadeType.ALL)
private Set<Movie> movie;

@Column(name ="genre")
private String genre;



public Genre() {

}



public Genre(Integer id,Set<Movie> movie,String genre) {
    super();
    this.id = id;
    this.movie = movie;
    this.genre = genre;
}



public Integer getId() {
    return id;
}



public void setId(Integer id) {
    this.id = id;
}

@JsonBackReference
public Set<Movie> getMovie() {
    return movie;
}


public void setMovie(Set<Movie> movie) {
    this.movie = movie;
}



public String getGenre() {
    return genre;
}



public void setGenre(String genre) {
    this.genre = genre;
}



}

MovieRestcontroller

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/video-library")
public class MovieController {

  @Autowired
  private  MoiveRepository movieRepository;



  //CRATE
  //Add movie
  @PostMapping("/movies")
  public Movie createMovie(@RequestBody Movie movie)
  {
    return movieRepository.save(movie);
  }

  //READ
  //Get a list of all movies
  @GetMapping("/movies")
  public List<Movie> getAllMovie(){
    return movieRepository.findAll();
  }

  //Get single movie
  @GetMapping("/movies/{id}")
  public ResponseEntity<Movie> getMovieById(@PathVariable Integer id){
    Movie movie = movieRepository.findById(id).orElseThrow(()->
      new ResourseNotFoundException("404 Error: Movie not exist with the Given "+id));
    return ResponseEntity.ok(movie);
  }

  //UPDATE
  //Updated movie
  @PutMapping("/movies/{id}")
  public ResponseEntity <Movie> updateMovie(@PathVariable Integer id,@RequestBody Movie movieDetails){
    Movie movie = movieRepository.findById(id).orElseThrow((() ->
      new ResourseNotFoundException("404 Error: Movie not exist with the Given "+id)));


    movie.setTitle(movieDetails.getTitle());
    movie.setRate(movieDetails.getRate());
//    movie.setGenre(movieDetails.getGenre());
    movie.setNumberInStock(movieDetails.getNumberInStock());

    Movie updateMovie = movieRepository.save(movie);
    Map<String,Boolean> response = new HashMap<>();
    response.put("Movie Updated Successfully",Boolean.TRUE);
    return  ResponseEntity.ok(updateMovie);
  }

  //DELETE
  //Delete movie
  @DeleteMapping("/movies/{id}")
  public ResponseEntity <Map<String,Boolean>> deleteMovie(@PathVariable Integer id){
    Movie employee = movieRepository.findById(id)
      .orElseThrow((() -> new ResourseNotFoundException("404 Error: Movie not exist with the Given "+id)));
    movieRepository.delete(employee);
    Map<String,Boolean> response = new HashMap<>();
    response.put("Movie Deleted Successfully",Boolean.TRUE);
    return ResponseEntity.ok(response);
  }
  
  
}

GenreController

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/video-library")
public class GenreController {
    @Autowired
    public GenreRepository genreRepository;
    
    
      @PostMapping("/genre")
      public Genre createGenre(@RequestBody Genre genre)
      {
        return genreRepository.save(genre);
      }
      
      @GetMapping("/genre")
      public List<Genre> getAllGenre(){
        return genreRepository.findAll();
      }


      @GetMapping("/genre/{id}")
      public ResponseEntity<Genre> getGenreById(@PathVariable Integer id){
        Genre genre = genreRepository.findById(id).orElseThrow(()->
          new ResourseNotFoundException("404 Error: Genre not exist with the Given "+id));
        return ResponseEntity.ok(genre);
      }
}

解决方法

尝试在pairSub LoopThroughFolder() Dim MyFile As String,Str As String,MyDir As String,Wb As Workbook Dim Rws As Long,Rng As Range,r As Range Set Wb = ThisWorkbook: Wb.Sheets(2).Range("L:L").ClearContents Dim FSO As Object,fld As Object,Fil As Object Dim wbkCS As Workbook Dim FolderPath As String Dim fsoFile As Object Dim fsoFol As Object Dim fileName As String Dim sWb As Workbook Dim MatchingColumn As Range Dim MatchingRowNb As Long MsgBox "Choose a folder: " Application.DisplayAlerts = False With Application.FileDialog(msoFileDialogFolderPicker) .InitialFileName = "C:\Users\" .AllowMultiSelect = False If .Show <> -1 Then MsgBox "No folder selected! Exiting script." Exit Sub End If FolderPath = .SelectedItems(1) End With If Right(FolderPath,1) <> "\" Then FolderPath = FolderPath + "\" End If Set FSO = CreateObject("Scripting.FileSystemObject") Set fld = FSO.GetFolder(FolderPath) If FSO.FolderExists(fld) Then For Each fsoFol In FSO.GetFolder(FolderPath).SubFolders For Each fsoFile In fsoFol.Files If Mid(fsoFile.Name,InStrRev(fsoFile.Name,".") + 1) = "xlsx" Then fileName = fsoFile.Name Application.ScreenUpdating = False MyDir = FolderPath 'fld fileName = Dir(MyDir & "*.xlsx") ChDir MyDir Application.ScreenUpdating = False Application.DisplayAlerts = False Do While fileName <> "" Set sWb = Workbooks.Open(fileName) With sWb.Worksheets(2) Rws = .Cells(Rows.Count,12).End(xlUp).Row Set Rng = Range(.Cells(5,1),.Cells(Rws,12)) End With With Wb.Worksheets(2) Set MatchingColumn = .Range(.Cells(5,.Cells(.Rows.Count,1).End(xlUp)) For Each r In Rng.Rows If r.Cells(1,1).Value2 <> vbNullString Then 'Ignoring empty rows If r.Rows.Hidden = False Then 'We find the row where the Ids matche MatchingRowNb = Application.Match(r.Cells(1,1).Value2,MatchingColumn,False) 'We add the current value in the cell with the new value comming from the other file .Cells(4 + MatchingRowNb,12).Value2 = .Cells(4 + MatchingRowNb,12).Value2 + r.Cells(1,12).Value2 End If End If Next End With sWb.Close SaveChanges:=True Application.DisplayAlerts = True fileName = Dir() Loop End If Next Next End If End Sub 注释中使用consumesproduces属性,例如:

@GetMapping

您传递了错误的请求。您的请求应包含@PostMapping作为对象。 尝试

@PostMapping(path = "/genre",consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)

@GetMapping(path = "/movies/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
,

您使用哪个客户端来测试REST API?

所有客户端都有选项,可让您根据请求设置Content-type:application/json标头。

在邮递员中,依次选择Body标签和raw,然后将右侧的TEXT更改为JSON

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-