我怎樣才能形成這樣的JSON:
{
"error": false,
"errorCode": 0,
"message": [{
"id": "93",
"venueName": "Sushi Kuni",
"venueAddress": "10211 S De Anza Blvd Cupertino CA",
"showDate": "1531022400",
"showTime": "",
"description": ""
}, {
"id": "38",
"venueName": "Two Keys Tavern",
"venueAddress": "333 S Limestone Lexington KY",
"showDate": "1531368000",
"showTime": "8 pm - 1 am",
"description": ""
}]
}
我嘗試創建具有一對一、多對一關系的模型。
@Entity
@Table(name = "tutorials")
public class Tutorial {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tutorial_generator")
private int id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "published")
private boolean published;
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comment_generator")
private int id;
@Lob
private String content;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "tutorial_id", nullable = false)
@JsonIgnore
private Tutorial tutorial;
控制器:
public ResponseEntity<List<Comment>> getAllCommentsByTutorialId(@PathVariable(value = "tutorialId") int tutorialId) {
if (!tutorialRepository.existsById(tutorialId)) {
throw new ResourceNotFoundException("Not found Tutorial with id = " tutorialId);
}
List<Comment> comments = commentRepository.findByTutorialId(tutorialId);
return new ResponseEntity<>(comments, HttpStatus.OK);
}
但我得到了
[
{
"id": 1,
"content": "asdaasfaf"
},
{
"id": 3,
"content": "ssaduy7tjyjt"
},
{
"id": 4,
"content": null
}
]
我閱讀了有關創建節點的資訊,但不明白如何將其與 spring 資料集成。我需要在表格教程中嵌套表格評論嗎?
uj5u.com熱心網友回復:
在我看來,您似乎非常接近預期的結果。首先,您應該向 Tutorial 物體添加一個成員:
@OneToMany(mappedBy = "tutorial_id")
private List<Comment> comments;
最后缺少的部分是讓您的控制器回傳一個教程實體:
public ResponseEntity<Tutorial> getTutorialWithComments(@PathVariable(value = "tutorialId") int tutorialId) {
Tutorial tutorial = tutorialRepository.findById(tutorialId)
.orElseThrows(() -> new ResourceNotFoundException("Not found Tutorial with id = " tutorialId));
return new ResponseEntity<>(tutorial, HttpStatus.OK);
}
我在沒有任何 IDE 幫助的情況下寫了這篇文章,所以請原諒任何錯誤。這個想法應該很清楚,您需要回傳一個包含評論串列的教程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/507079.html
