How to increment the parent entity version whenever a child entity gets modified with JPA and Hibernate

Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!


StackOverflow and the Hibernate forum are gold mines. Yesterday, I bumped on the following question on our forum:

Usually, the rationale behind clustering objects together is to form a transactional boundary inside which business invariants are protected. I’ve noticed that with the OPTIMISTIC locking mode changes to a child entity will not cause a version increment on the root. This behavior makes it quite useless to cluster objects together in the first place.

Is there a way to configure Hibernate so that any changes to an object cluster will cause the root object’s version to increment? I’ve read about OPTIMISTIC_FORCE_INCREMENT but I think this does increment the version regardless of if entities were changed or not. Since reads shouldn’t be conflicting with other reads in most scenarios, this doesn’t seem so useful either.

I could always increment the version inside every mutating behavior of the root, but that is quite error-prone. I’ve also thought of perhaps using AOP to do this, but before looking into it, I wanted to know if there were any easy way to do that. If there were a way to check if an object graph is dirty, then it would make it quite easy to implement as well.

What a brilliant question! This post is going to demonstrate how easy you can implement such a requirement when using Hibernate.

Domain Model

First, let’s assume we have the following entities in our system:

Domain Model Entities

The Post is the root entity, and it might have several PostComment entities. Every PostComment can have at most one PostCommentDetails. These entities are mapped as follows:

@Entity(name = "Post") 
@Table(name = "post")
public class Post {

    private Long id;

    private String title;

    private int version;

    //Getters and setters omitted for brevity

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment 
    implements RootAware<Post> {

    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;

    //Getters and setters omitted for brevity

    public Post root() {
        return post;

@Entity(name = "PostCommentDetails")
@Table(name = "post_comment_details")
public class PostCommentDetails 
    implements RootAware<Post> {

    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    private PostComment comment;

    private int votes;

    //Getters and setters omitted for brevity

    public Post root() {
        return comment.root();

As you probably noticed, the @OneToOne association uses the awesome @MapsId mapping which I already explained in this post.

The PostComment and PostCommentDetails entities are implementing the RootAware interface which is very straightforward:

public interface RootAware<T> {
    T root();

By implementing the RootAware interface, we can resolve the root entity for any PostComment and PostCommentDetails entity.

Event Listeners

Contrary to popular belief, Hibernate is not just an ORM framework but a very customizable data access platform. For our example, we need to intercept any child entity modification and acquire an OPTIMISTIC_FORCE_INCREMENT event on the associated root entity.

To intercept the UPDATE and the DELETE SQL events, the following custom entity event listener is needed:

public class RootAwareUpdateAndDeleteEventListener 
    implements FlushEntityEventListener {

    private static final Logger LOGGER = 

    public static final RootAwareUpdateAndDeleteEventListener INSTANCE = 
        new RootAwareUpdateAndDeleteEventListener();

    public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
        final EntityEntry entry = event.getEntityEntry();
        final Object entity = event.getEntity();
        final boolean mightBeDirty = entry.requiresDirtyCheck( entity );

        if(mightBeDirty && entity instanceof RootAware) {
            RootAware rootAware = (RootAware) entity;
            if(updated(event)) {
                Object root = rootAware.root();
      "Incrementing {} entity version because a {} child entity has been updated", 
                    root, entity);
                incrementRootVersion(event, root);
            else if (deleted(event)) {
                Object root = rootAware.root();
      "Incrementing {} entity version because a {} child entity has been deleted", 
                    root, entity);
                incrementRootVersion(event, root);

    private void incrementRootVersion(FlushEntityEvent event, Object root) {
        event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);

    private boolean deleted(FlushEntityEvent event) {
        return event.getEntityEntry().getStatus() == Status.DELETED;

    private boolean updated(FlushEntityEvent event) {
        final EntityEntry entry = event.getEntityEntry();
        final Object entity = event.getEntity();

        int[] dirtyProperties;
        EntityPersister persister = entry.getPersister();
        final Object[] values = event.getPropertyValues();
        SessionImplementor session = event.getSession();

        if ( event.hasDatabaseSnapshot() ) {
            dirtyProperties = persister.findModified( 
                event.getDatabaseSnapshot(), values, entity, session 
        else {
            dirtyProperties = persister.findDirty( 
                values, entry.getLoadedState(), entity, session 

        return dirtyProperties != null;

This event listener is going to be executed whenever an entity is flushed by the currently running Persistence Context. Every entity modification is automatically detected by the dirty checking mechanism and marked as dirty.

If the entity is dirty and implements the RootAware interface, then we can just lock the parent entity with an OPTIMISTIC_FORCE_INCREMENT lock type. This lock type is going to increment the root entity version during the flush operation.

To intercept when new child entities are being persisted, the following event listener is needed:

public class RootAwareInsertEventListener 
    implements PersistEventListener {

    private static final Logger LOGGER = 

    public static final RootAwareInsertEventListener INSTANCE = 
        new RootAwareInsertEventListener();

    public void onPersist(PersistEvent event) throws HibernateException {
        final Object entity = event.getObject();

        if(entity instanceof RootAware) {
            RootAware rootAware = (RootAware) entity;
            Object root = rootAware.root();
            event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);

  "Incrementing {} entity version because a {} child entity has been inserted", 
                root, entity);

    public void onPersist(PersistEvent event, Map createdAlready) 
        throws HibernateException {

To register these two event listeners, we need to provide a org.hibernate.integrator.spi.Integrator implementation:

public class RootAwareEventListenerIntegrator
    implements org.hibernate.integrator.spi.Integrator {

    public static final RootAwareEventListenerIntegrator INSTANCE = 
        new RootAwareEventListenerIntegrator();

    public void integrate(
            Metadata metadata,
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {

        final EventListenerRegistry eventListenerRegistry =


    public void disintegrate(
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        //Do nothing

When bootstrapping the JPA EntityManagerFactory, we can provide the RootAwareEventListenerIntegrator via the hibernate.integrator_provider configuration property:

    (IntegratorProvider) () -> Collections.singletonList(

To see how you can set the hibernate.integrator_provider configuration property when using Spring with JPA or Spring with Hibernate, check out this article.

Testing time

Assuming we have the following entities within our system:

doInJPA(entityManager -> {
    Post post = new Post();
    post.setTitle("High-Performance Java Persistence");

    PostComment comment1 = new PostComment();

    PostCommentDetails details1 = new PostCommentDetails();

    PostComment comment2 = new PostComment();

    PostCommentDetails details2 = new PostCommentDetails();


Updating child entities

When updating a PostCommentDetails entity:

PostCommentDetails postCommentDetails = entityManager.createQuery(
    "select pcd " +
    "from PostCommentDetails pcd " +
    "join fetch pcd.comment pc " +
    "join fetch p " +
    "where = :id", PostCommentDetails.class)
.setParameter("id", 2L)


Hibernate generates the following SQL statements:

SELECT  pcd.comment_id AS comment_2_2_0_ , AS id1_1_1_ , AS id1_0_2_ ,
        pcd.votes AS votes1_2_0_ ,
        pc.post_id AS post_id3_1_1_ , AS review2_1_1_ ,
        p.title AS title2_0_2_ ,
        p.version AS version3_0_2_
FROM    post_comment_details pcd
INNER JOIN post_comment pc ON pcd.comment_id =
INNER JOIN post p ON pc.post_id =
WHERE   pcd.comment_id = 2

UPDATE post_comment_details 
SET votes = 15 
WHERE comment_id = 2

UPDATE post 
SET version = 1 
where id = 1 AND version = 0

As you can see, not only the post_comment_details row gets updated but the post version is also incremented.

The same goes for the PostComment entity modifications:

PostComment postComment = entityManager.createQuery(
    "select pc " +
    "from PostComment pc " +
    "join fetch p " +
    "where = :id", PostComment.class)
.setParameter("id", 2L)


Hibernate generating the following SQL statements:

SELECT AS id1_1_0_ , AS id1_0_1_ ,
        pc.post_id AS post_id3_1_0_ , AS review2_1_0_ ,
        p.title AS title2_0_1_ ,
        p.version AS version3_0_1_
FROM    post_comment pc
INNER JOIN post p ON pc.post_id =

UPDATE post_comment 
SET post_id = 1, review = 'Brilliant!' 
WHERE id = 2

UPDATE post 
SET version = 2 
WHERE id = 1 AND version = 1

Adding new child entities

The parent Post entity version is incremented even when a new child entity is being persisted:

Post post = entityManager.getReference(Post.class, 1L);

PostComment postComment = new PostComment();
postComment.setReview("Worth it!");

Hibernate generates the following SQL statements:

SELECT AS id1_0_0_ ,
       p.title AS title2_0_0_ ,
       p.version AS version3_0_0_
FROM   post p

INSERT INTO post_comment (post_id, review, id) 
VALUES (1, 'Worth it!', 3)

UPDATE post 
SET version = 3 
WHERE id = 1 AND version = 2

Removing child entities

This solution works even when removing existing child entities:

PostComment postComment = entityManager.getReference(PostComment.class, 3l);

Hibernate being able to increment the parent entity version accordingly:

SELECT AS id1_1_0_ ,
       pc.post_id AS post_id3_1_0_ , AS review2_1_0_
FROM   post_comment pc

SELECT AS id1_0_0_ ,
       p.title AS title2_0_0_ ,
       p.version AS version3_0_0_
FROM   post p

DELETE FROM post_comment 
WHERE id = 3

UPDATE post 
SET version = 4 
WHERE id = 1 and version = 3

Cool, right?

Online Workshops

If you enjoyed this article, I bet you are going to love my upcoming Online Workshops!


Synchronizing a root entity version for every child entity modification is fairly easy with Hibernate. Hibernate supports many concurrency control mechanisms, as illustrated in this comprehensive tutorial.

Code available on GitHub.

Transactions and Concurrency Control eBook

16 Comments on “How to increment the parent entity version whenever a child entity gets modified with JPA and Hibernate

  1. Hello, I have a question. Is there is any way to also modify LastModifiedDate field in root entity using event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT) from within listener? I’ve tried to use @PreUpdate and @LastModifiedDate Spring’s annotation but only version field increments.

    • The LockModeType.OPTIMISTIC_FORCE_INCREMENT can only increase the version on a separate entity. The last_modify_date makes sense for cases when the row state gets modified, not when the version is the only field that gets incremented since the version has a purpose only for the concurrency control mechanism.

      You could use a database trigger to achieve your goal. Or, you could try to debug Hibernate and see whether there is a way you could wire a listener after the LockModeType.OPTIMISTIC_FORCE_INCREMENT is set. I could also check out a solution for you via consulting if you’re interested.

  2. Very usefull article. Thank you very much for the content.

    What about ManyToMany Relationships?

    My naive Implement uses the AuditAware-Interface and returns a list of Objects.
    public Set root() {
    return this.parents;

    This is working fine for the deleted branch in RootAwareUpdateAndDeleteEventListener.onFlushEntity but for some reason the update-Branch the root-Method returns an empty persistent set.

    • The many-to-many association links to parent entities, hence the only think you need to track is the change in the collection state. There is a collection update event you could track and propagate the version to the parent.

      • Thank you for the link but I already did read your book 🙂

        OneToMany relation is totally fine in my case (small bounded collection). Switching to ManyToOne would just complexify the use case and don’t provide performance improvement.

        I’m just trying to figure out a way to have a consistent versionning on my aggregate root (because my entity are only modified through the aggregate root).

      • You could try intercepting the PostCollectionUpdateEvent

      • Unfortunately this event is only triggered when the collection itself is edited (appending, removing, and probably reordering). Also, when the collection itself is edited, the versioning is already updated in this case. But not when an entity of the collection (owned by the aggregate) is edited.

      • In this case, it might not work unless you use a bidirectional association

  3. The updated check in the RootAwareUpdateAndDeleteEventListener(line 57 in the snippet) causes a nullpointer when the previous state (from entry.getLoadedState()) is null.

    Reproduced by:
    -open transaction
    -persist a new entity
    -flush and clear the session
    -call pesist on the same entity again
    -flush the session -> nullpointer

    • Thanks for the tip. All the code is on GitHub, so you can send a replicating test case. Also, why do you call persist the second time? Persist is for new entities only.

      • Thanks for the fast reply, I will try to write a test case later today. My code actually uses the saveOrUpdate method on the session, I just confused the two when writing the comment.

      • The saveOrUpdate is merely an alias for upate. You should favor persist for new entities. The update is for forcing an update on detached entities.

  4. I had the same problem. I wanted the owning entity’s “lastModifiedDate” and “Version” fields update when the child entities change. I have tested so many things and implemented lots of custom code. Even I was trying to implement a custom dirty check mechanism. nothing worked for auditing. Finally, Using Hibernate Bytecode Enhancement Maven plugin and enabling DirtyTracking fixed the issue of parent versioning and auditing for me. Now the owning entity’s “lastModifiedDate” and “version” updates by itself and without any custom code when I edit the child. Bear in mind that I have only tested ManyToOne/OneToMany relation but I think this should work for other relations as well. Also, I am updating the entity from the owning side (using Spring Data)

  5. These changes are always executed in the context of a database transaction. Hibernate cannot modify data without an explicit transaction.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Hypersistence Optimizer 2.2 has been released!