Reputation: 455
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.
Upvotes: 2
Views: 3217
Reputation: 154070
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:
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.
idbag
are a legacy hibernate mapping and they were used to provide a more efficient unidirectional associations alternativeYou 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.
Upvotes: 7