Hibernate / Hibernate 7 Basics Interview Questions
What is optimistic locking in Hibernate 7 and how do you implement it?
Optimistic locking uses a version column to detect concurrent update conflicts at commit time instead of locking the row. Hibernate 7 throws OptimisticLockException when the version has changed since the entity was loaded.
@Entity public class Product { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; private BigDecimal price; @Version // Hibernate manages automatically private Long version; } // How it works: // Load: SELECT id, name, price, version FROM products WHERE id=1 // version=5 // Modify: product.setPrice(new BigDecimal("99")) // Flush: UPDATE products SET price=99, version=6 WHERE id=1 AND version=5 // If another TX updated it: version!=5 -> OptimisticLockException! // Handling conflicts: for (int attempt = 0; attempt < 3; attempt++) { try (Session session = sf.openSession()) { session.beginTransaction(); Product p = session.find(Product.class, productId); p.setPrice(p.getPrice().multiply(new BigDecimal("0.9"))); session.getTransaction().commit(); break; // success } catch (OptimisticLockException e) { if (attempt == 2) throw e; Thread.sleep(50 * (attempt + 1)); } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
