@OrderColumn persists each element’s position in a List through an additional database column. Indexes start at zero, must remain contiguous, and default to a derived order-column name unless explicitly configured. section 8.1.6 section 9.2.2
Persisting an ordered element collection
An element collection can preserve image order with `@OrderColumn`: `@ElementCollection` `@CollectionTable(name = "IMAGE")` `@OrderColumn` `@Column(name = "FILENAME")` `private List<String> images = new ArrayList<>();` The order column defaults to `IMAGES_ORDER`. For a list containing A, B, and C, removing A deletes its row and updates B and C to shift their indexes left. section 8.1.6
Listing 8.5 Persistent list, preserving the order of elements in the database
Path: Ch08/mapping-collections/src/main/java/com/manning/javapersistence /ch08/listofstrings/Item.java @Entity public class Item { // . . . @ElementCollection @CollectionTable(name = "IMAGE") @OrderColumn // Enables persistent order, Defaults to IMAGES_ORDER @Column(name = "FILENAME") private List<String> images = new ArrayList<>();
Use this mapping when the database must preserve the order of list elements in an element collection. section 8.1.6
For a one-to-many List, combine @OrderColumn with a join column. A named, non-null order column such as BID_POSITION makes the stored index explicit. In a bidirectional mapping, the @ManyToOne side remains the relationship owner, while the collection side must write indexes; duplicate the join column and disable writes on the many-to-one side. section 9.2.2
Path: onetomany-list/src/main/java/com/manning/javapersistence/ch09/ onetomany/list/Item.java @Entity public class Item { @OneToMany @JoinColumn( name = "ITEM_ID", nullable = false ) @OrderColumn( name = "BID_POSITION", #1 nullable = false #2 ) private List<Bid> bids = new ArrayList<>(); // . . . } #1 As mentioned, this is a unidirectional mapping: there is no other “mapped by” side. The <kbd>Bid</kbd> doesn’t have a <kbd>@ManyToOne</kbd> property. The <kbd>@OrderColumn</kbd> annotation will set the name of the index column to be <kbd>BID_POSITION</kbd>. Otherwise, it would default to <kbd>BIDS_ORDER</kbd>. #2 As usual, we should make the column <kbd>NOT NULL</kbd>.
Use this listing as a concrete unidirectional one-to-many mapping with an explicit, non-null order column. section 9.2.2
Evaluate the operational consequences before choosing persistent ordering:
- Expect Hibernate to issue one UPDATE for each element shifted after a removal or middle insertion; clearing the list uses a single DELETE. section 8.1.6 section 9.2.2
- Prefer query-based sorting when display order can change or users need alternate views such as newest, highest, filtered, or time-ranged results. section 8.1.6 section 9.2.2
