繁体   English   中英

一对多映射休眠

[英]One to Many Mapping Hibernate

我试图在数据库的 Comment 表中使用 post 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);

您正在创建总共 3 个评论实例(因此数据库表中有 3 条记录),而不是每个帖子 3 个实例。

当您更新 post1 评论时,您将 post2 评论作为参数,因此从评论到 post2 的外键将更改为 post1。

如果您希望每个帖子有 3 条评论,则总共需要 6 个评论实例(2 条帖子 * 3 条评论)

发生这种情况是因为您放置了相同的评论对象,然后休眠考虑要将评论的连接从post2post1

因此,您必须再次构建三个注释。

    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 With Comment
    Post post1 = new Post("1st Post", "1st Post Description", new ArrayList<Comments>(), 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);

这样,就创建了其他三个对象用于注释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM