liveBook · Manning

Bag

As explained in Java Persistence with Spring Data and Hibernate epub

A persistent unordered collection that permits duplicate element values and does not assign a collection index to them.

A bag is an unordered persistent collection that permits duplicate element values and ignores element indexes. In Java, map it with Collection and commonly initialize it with ArrayList. Hibernate stores the elements without maintaining list positions or enforcing set-style uniqueness. section 8.1.5

Choose a bag when the collection semantics and database design support these conditions:

  • Use a surrogate collection-table key when duplicate values must be distinguishable; Hibernate’s proprietary @CollectionId supplies this identifier. section 8.1.5 section 8.2.3
  • Prefer a bag over a List when order is irrelevant, and over a Set when duplicate values are valid. section 8.1.5 section 9.2.1
  • For a bidirectional one-to-many association, a bag can add a new entity without loading the existing collection, improving behavior for potentially large collections. section 9.2.1
  • Avoid eager-fetching two bag collections simultaneously because separate collection queries can produce an undesirable Cartesian product. section 9.2.1

Bag of entity references

A bidirectional one-to-many mapping can declare the collection as Collection<Bid> while retaining the association owner on Bid: @OneToMany(mappedBy = "item") private Collection<Bid> bids = new ArrayList<>(); Adding a new Bid can persist it without loading every existing bid, provided the collection is not iterated.

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains Java mappings, surrogate collection keys, duplicate handling, lazy insertion, and multiple-bag fetch limits.
Examples
Uses bags of strings, embeddable images, and bidirectional Item-to-Bid associations with duplicate-addition and SQL-loading tests.
What you can do after
Apply it via Hibernate annotations to map duplicate-capable collections and assess their loading, fetching, and schema consequences.
How it connects
Compares bags with lists and sets, and connects them to element collections, embeddable components, one-to-many associations, and many-to-many join tables.

Also explained in

Compare how 2 books explain bag →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.