A forced version increment advances an entity’s version so that concurrent operations can become detectable conflicts, even when the entity itself is not modified. It is useful when inserting or changing related data should count as a change to an aggregate root. section 11.2.2
Concurrent auction bids
Placing a bid involves reading the highest bid, comparing it with the new bid, and storing the new bid if it is higher. Another bid can arrive between the read and insert. Versioning the Item alone does not detect this race if the Item is never modified. Finding the Item with LockModeType.OPTIMISTIC_FORCE_INCREMENT forces its version to advance, making the conflict detectable. section 11.2.2
Listing 11.5 Forcing a version increment of an entity instance
Path: /Ch11/transactions/src/test/java/com/manning/javapersistence/ch11 /concurrency/Versioning.java – forceIncrement() EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Item item = em.find( #1 Item.class, ITEM_ID, LockModeType.OPTIMISTIC_FORCE_INCREMENT ); Bid highestBid = queryHighestBid(em, item); // . . . Another transaction changes the record Bid newBid = new Bid( new BigDecimal("45.45"), item, highestBid); em.persist(newBid); #2 assertThrows(RollbackException.class, () -> em.getTransaction().commit()); #3 em.close(); #1 <kbd>find()</kbd> accepts a <kbd>LockModeType</kbd>. The <kbd>OPTIMISTIC_FORCE_INCREMENT</kbd> mode tells Hibernate that the version of the retrieved <kbd>Item</kbd> should be incremented after loading, even if it’s never modified in the unit of work. #2 The code persists a new <kbd>Bid</kbd> instance; this doesn’t affect any values of the <kbd>Item</kbd> instance. A new row is inserted into the <kbd>BID</kbd> table. Hibernate wouldn’t detect concurrently made bids without a forced version increment of the <kbd>Item</kbd>. #3 When flushing the persistence context, Hibernate executes an <kbd>INSERT</kbd> for the new <kbd>Bid</kbd> and forces an <kbd>UPDATE</kbd> of the <kbd>Item</kbd> with a version check. If someone modified the <kbd>Item</kbd> concurrently or placed a <kbd>Bid</kbd> concurrently with this procedure, Hibernate throws an exception.
The transaction requests a forced increment when finding the Item, persists a Bid, and expects a rollback on commit after a concurrent change. section 11.2.2
The mapping matters: with an @ElementCollection of Item bids, adding a bid increments the Item version, so a forced increment is unnecessary. With a Bid-to-Item @ManyToOne association, the bid operation can leave the Item unchanged. section 11.2.2
