JPA - EntityManager.lock Examples

Code Snippets JPA JAVA EE 

    private static void updateArticle() {
System.out.println("-- updating article --");
EntityManager em = entityManagerFactory.createEntityManager();
Article article = em.find(Article.class, 1L);
em.getTransaction().begin();
em.lock(article, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
if (article.getContent().length() < 5) {
article.setContent("updated content");
}
em.getTransaction().commit();
em.close();
System.out.println("Article updated : " + article);
}
Original Post




    private static void employeeUpdate() {
EntityManager em = entityManagerFactory.createEntityManager();
Employee employee = em.find(Employee.class, 1L);
em.getTransaction().begin();
em.lock(employee.getDepartment(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
employee.setSalary(3000);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-- updating employee --");
em.getTransaction().commit();
em.close();
System.out.println("Employee updated 1: " + employee);
}
Original Post




See Also