Vaishu13 Vaishu13 - 5 months ago 18
Java Question

Hibernate bag vs idbag

I have looked at the difference between a bag and idbag and I understand the difference between them but what I am trying to understand is would there be a scenario where things could go wrong if bag is used instead of idbag or vice versa. Can some one explain this with an example.

Answer

Bag is an unordered collection, and, unlike idbag, it doesn't use an extra column for storing each element index.

There's no such thing as a use case where a bag would work and an idbag would not. The only difference is their efficiency:

  1. Bags are the most efficient inverse collection but they perform poorly for unidirectional one-to-many associations:

Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows. Hibernate resolves this problem by completely removing in a single DELETE and recreating the collection whenever it changes. This can be inefficient.

  1. idbag are a legacy hibernate mapping and they were used to provide a more efficient unidirectional associations alternative

You can define an idbag semantics using the JPA @OrderColumn annotation:

@OneToMany(mappedBy = "department")
@OrderColumn(name = "index_id")
private List<Employee> employees;

This way you can use both Lists and Sets for ordering collections.

So, try to stick to bidirectional associations as they are the most efficient ones and they mimic the database relations better. If you want a certain element index strategy, use the @OrderColumn association.