У меня странный баг в моем коде, и я не знаю, почему это происходит (создание REST API).
У меня есть sheetmusi c таблица и таблица комментариев . Sheetmusi c может иметь несколько комментариев от разных пользователей. Таким образом, класс sheetmusi c содержит список комментариев.
Когда я пытаюсь получить по номеру sheetmusi c, он возвращает sheetmusi c и комментарии (что хорошо). Но у каждого комментария также есть sheetmusi c. У этого sheetmusi c снова есть комментарий, и у этого комментария снова есть sheetmusi c. Я думаю, что вы видите, что идет;).
sheetmusi c должен просто содержать все комментарии, а комментарий не должен содержать sheetmusi c, иначе он будет перехватывать.
Поэтому я использую несколько классов:
CommentController
package server.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import server.entity.Comment;
import server.entity.SheetMusic;
import server.repository.CommentRepository;
import server.repository.SheetMusicRepository;
import java.util.List;
import java.util.Map;
@RestController
public class CommentController {
@Autowired
CommentRepository commentRepository;
@Autowired
SheetMusicRepository sheetMusicRepository;
@PostMapping("/comments")
public Comment create(@RequestBody Map<String,String> body){
int sheetId = Integer.parseInt(body.get("sheetId"));
int userId = Integer.parseInt(body.get("userId"));
String title = body.get("title");
String description = body.get("description");
int score = Integer.parseInt(body.get("score"));
SheetMusic sheetMusic = sheetMusicRepository.findById(sheetId).orElse(null);
Comment comment = new Comment(sheetMusic,userId,title,description,score);
return commentRepository.save(comment);
}
}
Класс комментариев
package server.entity;
import javax.persistence.*;
@Entity
@Table(name = "comment")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "user_id")
private int userId;
// @ManyToOne
// private User user;
//
// public int getUsername(){
// return user.getUsername();
// }
private String title;
private String description;
private int score;
// Een comment hoort maar bij 1 sheetmusic
// Relatie op basis van het sheet_music_id
@ManyToOne
@JoinColumn(name="sheet_music_id", nullable = false)
private SheetMusic sheetMusic;
public Comment() {
}
public Comment(SheetMusic sheetMusic, int userId, String title, String description, int score) {
this.sheetMusic = sheetMusic;
this.userId = userId;
this.title = title;
this.description = description;
this.score = score;
}
public int getId() {
return id;
}
// Dit laat de sheet music id zien in json
public int getSheet_music_id(){
return this.sheetMusic.getId();
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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 int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
package server.entity;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name="sheet_music")
public class SheetMusic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
private String title;
private String componist;
private String key;
private String instrument;
// Een sheetmusic heeft meerdere comments
// mappedBy = "sheetMusic" is de variabele naam in de Comment entity
@OneToMany(mappedBy = "sheetMusic")
List<Comment> comments = new ArrayList<>();
@Lob
@Type(type="org.hibernate.type.BinaryType")
private byte[] pdf;
public SheetMusic() {
}
public SheetMusic(String title, String componist, String key, String instrument, byte[] pdf) {
this.title = title;
this.componist = componist;
this.key = key;
this.instrument = instrument;
this.pdf = pdf;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getComponist() {
return componist;
}
public void setComponist(String componist) {
this.componist = componist;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getInstrument() {
return instrument;
}
public void setInstrument(String instrument) {
this.instrument = instrument;
}
public byte[] getPdf() {
return pdf;
}
public void setPdf(byte[] pdf) {
this.pdf = pdf;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}