如何解决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);
}
}
解决方法
尝试在pair
和Sub 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
注释中使用consumes
和produces
属性,例如:
@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 举报,一经查实,本站将立刻删除。