Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Removing one tag from a post (post.getTags().remove(tag)) produces DELETE FROM post_tag WHERE post_id = ? followed by 49 INSERT statements. What is the cause and the fix?

The tags collection is a List without an order column, so Hibernate maps it as a bag. A bag allows duplicates, so a (post_id, tag_id) pair does not identify one link row, and Hibernate cannot delete just the removed tag; it deletes every link row of the post and re-inserts the 49 that remain. The fix is to change the collection to a Set with a correct equals and hashCode on Tag, or to model the link as an entity with its own id, and then prove it with SQL logging and a statement count test.

Why this question is asked

The SQL log in the question is a classic sign of a mapping problem rather than a code problem: the Java code does the smallest possible change, and the database receives fifty statements. On a busy blog or product catalogue, that multiplies lock time, replication traffic and the chance of deadlocks. Interviewers ask this because it is easy to spot once you know the bag rule and puzzling if you do not. In this answer, we will recap how the post_tag table is managed, reproduce the problem, fix it with a Set, look at the join entity alternative, and write a test that keeps it fixed.

1A Quick Recap: Who Writes post_tag

Post and Tag are linked by a @ManyToMany, stored in a link table post_tag with the columns post_id and tag_id. Hibernate owns that table completely: when we add a tag to post.getTags(), it inserts a row, and when we remove one, it must delete a row. The link rows have no id, so Hibernate can only identify them by their column values.

Hibernate uses different strategies depending on the collection's semantics. For a set, every element is unique, so the pair of keys identifies one row. For a list with an @OrderColumn, the position identifies a row. For a plain List with neither, Hibernate calls the collection a bag: no order, duplicates allowed, and therefore no reliable way to identify a single row.

2Reproducing the 1 Delete and 49 Inserts

Here is the mapping that causes it and what happens when one tag is removed from a post with 50 tags.

Java
@Entity
public class Post {
@Id @GeneratedValue Long id;
@ManyToMany
@JoinTable(name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private List<Tag> tags = new ArrayList<>(); // a bag
}
post.getTags().remove(java);
// delete from post_tag where post_id = ?
// insert into post_tag (post_id, tag_id) values (?, ?) x 49
Step throughWhat Hibernate does at flush for a changed collection
  1. Is the collection a Set?
    YesDelete or insert only the changed pairsNoNext check
  2. Does it have an @OrderColumn?
    YesUpdate rows by positionNoIt is a bag
  3. Bag changeddelete all links of the owner
  4. Recreateinsert every remaining element

4 steps in order. Play them, or step through them one at a time.

A plain List lands in the expensive branch.

The reason is that a bag might contain the same tag twice, and post_tag could then hold two identical rows. A statement such as DELETE ... WHERE post_id = 1 AND tag_id = 7 would delete both, which is wrong if only one occurrence was removed. Rather than guess, Hibernate takes the always-correct route: clear the post's links and write the current collection again. Correct, but expensive.

3Fix 1: Change the Collection to a Set

Switching to a Set tells Hibernate the elements are unique, so the pair (post_id, tag_id) identifies exactly one row. The removal becomes a single targeted delete.

Java
@ManyToMany
@JoinTable(name = "post_tag", ...)
private Set<Tag> tags = new HashSet<>();
@Entity
public class Tag {
@Id @GeneratedValue Long id;
@NaturalId @Column(unique = true, nullable = false) private String name;
@Override public boolean equals(Object o) {
return this == o || (o instanceof Tag t && name.equals(t.name));
}
@Override public int hashCode() { return name.hashCode(); }
}
post.getTags().remove(java);
// delete from post_tag where post_id = ? and tag_id = ? (1 statement)

Notice the equals and hashCode. A HashSet places and finds elements by hashCode and equals, so these must be stable for the whole life of the entity. Using the tag's unique name, a natural key, is ideal because it is known before the tag is saved. If we only have the generated id, equals must handle the null id of a new tag, and hashCode should return a constant per class so it does not change after persist. The default Object identity also works within one persistence context, but breaks when the same tag is loaded in different sessions or detached.

We should also give post_tag a primary key on (post_id, tag_id). It enforces the uniqueness that the Set assumes, so the database and the mapping agree.

4Fix 2: Model the Link as an Entity

If the link might ever need data of its own, such as who tagged the post and when, we can replace the @ManyToMany with a PostTag entity that has its own id and two @ManyToOne associations. Every link row then has an identity, and removing one is a single delete by id. Post can keep a @OneToMany(mappedBy = "post", orphanRemoval = true) collection of PostTag with helper methods, or tags can be managed through a repository. This costs a little more code but makes the link table visible, queryable and extensible.

5Verifying With Logging and a Statement Count Test

We confirm the fix with SQL logging in a test (spring.jpa.show-sql or the org.hibernate.SQL logger at debug level), and then lock it in with an assertion on the number of statements, so a future change back to List fails the build.

Java
@Test
void removingOneTagIssuesOneDelete() {
Post post = posts.save(postWithTags(50));
em.flush(); em.clear();
Post loaded = posts.findById(post.getId()).orElseThrow();
loaded.getTags().size(); // load the tags before counting
stats.clear(); // Hibernate Statistics, generate_statistics=true
loaded.getTags().remove(tag("java"));
em.flush();
assertThat(stats.getPrepareStatementCount()).isEqualTo(1); // 1 delete; 50 with the bag mapping
}

Notice that we load the collection before clearing the statistics, so the count covers only the flush. With the bag mapping, and JDBC batching off as it is by default, the same test reports 50 statements; with batching on, count executed statements with a DataSource proxy instead. A DataSource proxy that counts DELETE and INSERT statements is an equally good alternative if the team already uses one.

6Follow-up questions

Would adding @OrderColumn to the List also fix it?

It removes the full rewrite, because rows can be addressed by position. But removing from the middle shifts the position of every later tag, so Hibernate updates those rows instead. For tags, where order means nothing, a Set is the simpler and cheaper fix.

Does changing List to Set affect join fetching?

It removes MultipleBagFetchException when fetching tags together with another collection, but the SQL still returns a Cartesian product of rows. For large collections, separate queries remain faster.

Why not Lombok's generated equals and hashCode on Tag?

Generated versions usually include every field, including the id and lazy associations, so the hash changes after persist and can trigger lazy loading. Entities need hand-written equals based on a stable key.

7Conclusion

In this answer, we traced the 1 delete and 49 inserts to the bag mapping of a List without an order column: Hibernate cannot identify a single link row in a bag, so it rewrites the whole collection. We fixed it by switching to a Set with equals and hashCode on a stable key such as the tag name, backed by a composite primary key, or by modelling the link as an entity with its own id, and we verified the fix with SQL logging and a test that asserts the removal is a single statement.

What to say in the interviewAbout 80 seconds aloud

Open with

The tags field is a List without an order column, so Hibernate maps it as a bag, which allows duplicates. In a bag, the pair post_id and tag_id doesn't uniquely identify one row in post_tag, so Hibernate can't safely delete only the removed tag.

Then, if they want more

It falls back to the always-correct approach: delete all link rows for the post and insert the remaining 49. The fix is to change the collection to a Set. Then each pair is unique and the removal becomes a single delete where post_id and tag_id match.

For that to work the Tag entity needs a stable equals and hashCode, ideally on a natural key like the unique tag name, or an id-based version that copes with a null id and uses a constant hash code. I'd also make sure post_tag has a composite primary key so the database enforces uniqueness too.

If the link ever needs its own data, like who added the tag and when, I'd model it as a PostTag entity with its own id instead of a ManyToMany.

Then I'd verify it: turn on SQL logging in a test, and add a statement count assertion that removing one tag is a single delete, so nobody quietly switches it back to a List.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Removing one tag from a post (post.getTags().remove(tag)) produces DELETE FROM post_tag...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/0803647bca/