簡體   English   中英

如何使用Spring Boot發布oneToMany關系數據庫條目

[英]How to POST oneToMany relational database entries with Spring Boot

我應該如何構造JSON POST,后端的控制器和POJO類?

這是用於Twitter克隆的,因此用戶可以有多個Tweet等

POST

{ "tweet": "Sew one button, doesn't make ua tailor", "user": "Alex" }

推特控制器

    public Tweet createTweet(@RequestBody Tweet tweet) {
        return tweetRepository.save(tweet);
    }

推文類

@Table(name = "tweets")
public class Tweet {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    private User user;

    ...

用戶類別

@Table(name = "custom_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "tweet_id")
    private List<Tweet> tweet = new ArrayList<>();

這是我得到的回應

{
    "id": 1,
    "user": {
        "id": 2,
        "name": "Alex",
        "tweet": []
    },
    "tweet": "Sew one button, doesn't make u a tailor"
}

編輯:

如果我在用戶端點上執行GET,這就是我所得到的(應該包括相關的推文)

[
    {
        "id": 2,
        "name": "Alex",
        "tweet": []
    }
]

這里:

{
    "id": 1,
    "user": {
        "id": 2,
        "name": "Alex",
        "tweet": []
    },
    "tweet": "Sew one button, doesn't make u a tailor"
}

從外觀上看,您的Tweet對象具有tweet屬性,而User對象具有一個數組,該數組映射與該用戶相關的每個tweet,該示例上當前為空。

在我看來,這就像您在Tweet和U​​ser之間的雙向映射上的問題一樣。 考慮在雙向關系上使用mapledBy屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM