Close

JPA - Using OPTIMISTIC_FORCE_INCREMENT lock mode to force version increment

[Last Updated: Nov 15, 2018]

LockModeType.OPTIMISTIC_FORCE_INCREMENT can be used to apply optimistic lock with version update. In this mode, the version is increased even though there's no change with the entity. In LockModeType.OPTIMISTIC mode, however, version does not increase if there's no changes with the target entity.

Example

The Entity

@Entity
public class Article {
  @Id
  @GeneratedValue
  private long id;
  @Version
  private long version;
  private String content;
    .............
}

Using OPTIMISTIC_FORCE_INCREMENT

public class ForceIncrementExample {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistArticle();
          updateArticle();
      } finally {
          entityManagerFactory.close();
      }
  }

  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);
  }

  public static void persistArticle() {
      System.out.println("-- persisting article --");
      Article article = new Article("test article");
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(article);
      em.getTransaction().commit();
      em.close();
      System.out.println("Article persisted: " + article);
  }
}
-- persisting article --
Article persisted: Article{id=1, version=0, content='test article'}
-- updating article --
Article updated : Article{id=1, version=1, content='test article'}

As seen above, the Article's version has increased even though there's was no change with the entity.

In the next example we will see a use case of this locking mode.

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.12.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

OPTIMISTIC_FORCE_INCREMENT Example Select All Download
  • optimistic-force-increment-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ForceIncrementExample.java
          • resources
            • META-INF

    See Also