I'm trying to persist 6 comments with a foreign key of post id in the Comment table in the database, but the last 3 comments override the first 3 comments with a newly added foreign key.
Test class:
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)
post1.setComments(arrayList);
post1.setUpdatedAt(new Date(System.currentTimeMillis()));
postReposetory.save(post1);
CodePudding user response:
You are creating a total of 3 comments instances, not 3 instances per post. When you update post1 comments you are giving post2 comments as argument, so the foreign key from comments to post2 will change to post1. If you want to have 3 comments per post you need 6 comments instances total (2 posts * 3 comments).
CodePudding user response:
This happens because you put the same objects of comments and then hibernate consider that you want to change the connections of the comments from post2
to post1
.
Therefore you have to construct again the three comments.
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);
In this way, other three objects are created for comments.