I'm trying to keep 6 comments in the Comment table of the database using a foreign key to the post id, but the last 3 comments overwrite the first 3 comments with the 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 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);
You create a total of 3 comment instances (and therefore 3 records in the database table), not 3 instances per post.
When you update the post1 comment, you take the post2 comment as a parameter, so the foreign key from comments to post2 will change to post1.
If you want 3 comments per post, you will need a total of 6 comment instances (2 posts * 3 comments).
This happens because you put the same annotation object and then hibernate thinks you want to change the connection of the annotation from
post2
topost1
.So you have to rebuild these three annotations.
This creates another three objects for comments.