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)); } }
More Related questions...