搜尋

首頁  >  問答  >  主體

一對多映射 Hibernate

我試圖在資料庫的 Comment 表中使用帖子 id 的外鍵保留 6 條評論,但最後 3 條評論使用新添加的外鍵覆蓋了前 3 條評論。

測試類別:

Comments comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
Comments comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
Comments comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));

ArrayList<Comments> arrayList = new ArrayList<>();
arrayList.add(comments);
arrayList.add(comments2);
arrayList.add(comments3);

// Insert Without Comment
Post post1 = new Post("1st Post", "1st Post Description", new ArrayList<Comments>(), new Date(System.currentTimeMillis()));
postReposetory.save(post1);

// Insert With Comment
Post post2 = new Post("2st Post", "2st Post Description", arrayList, new Date(System.currentTimeMillis()));
postReposetory.save(post2);

// Update (Insert Comment)
post1.setComments(arrayList);
post1.setUpdatedAt(new Date(System.currentTimeMillis()));
postReposetory.save(post1);

P粉770375450P粉770375450261 天前482

全部回覆(2)我來回復

  • P粉038161873

    P粉0381618732024-04-02 11:19:49

    您總共建立了 3 個評論實例(因此資料庫表中有 3 筆記錄),而不是每個貼文 3 個實例。

    當您更新 post1 評論時,您會將 post2 評論作為參數,因此從 comments 到 post2 的外鍵將變更為 post1。

    如果您希望每個貼文有 3 則評論,則總共需要 6 個評論實例(2 個貼文 * 3 則評論)

    回覆
    0
  • P粉187677012

    P粉1876770122024-04-02 00:07:37

    發生這種情況是因為您放置了相同的註釋對象,然後 hibernate 認為您想要將註釋的連接從 post2 更改為 post1

    因此您必須重新建構這三個註解。

        Comments comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
        Comments comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
        Comments comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));
    
        ArrayList arrayList = new ArrayList<>();
        arrayList.add(comments);
        arrayList.add(comments2);
        arrayList.add(comments3);
    
        // Insert With Comment
        Post post1 = new Post("1st Post", "1st Post Description", new ArrayList(), new Date(System.currentTimeMillis()));
        postReposetory.save(post1);
        
        // Insert Without Comment
        Post post2 = new Post("2st Post", "2st Post Description", arrayList, new Date(System.currentTimeMillis()));
        postReposetory.save(post2);
    
        // Update (Insert Comment)
        comments = new Comments("1st Comment", new Date(System.currentTimeMillis()));
        comments2 = new Comments("2st Comment", new Date(System.currentTimeMillis()));
        comments3 = new Comments("3st Comment", new Date(System.currentTimeMillis()));
        post1.setComments(List.of(comments, comments2, comments3));
        post1.setUpdatedAt(new Date(System.currentTimeMillis()));
        postReposetory.save(post1);
    

    這樣就創建了另外三個物件用於評論。

    回覆
    0
  • 取消回覆