How to update a Timestamp property when only some entity fields get modified with JPA and Hibernate

#1

I have an entity lets say Employee as below:

Id(primary key)
Firstname
Lastname
DateofBirth
CreatedDate

I need to update the created date only if there is any change in firstname or lastname or dateofbirth.

Any suggestion on how to implement this.
I am using spring boot with jpa.

Thanks in advance

0 Likes

#2

You have multiple options:

  1. You can update the createdDate in the setters:

     public void setFirstName(String firstName) {
     	this.firstName = firstName;
     	this.createdDate = new Date();
     }
    
  2. You can register a FlushEntityEventListener that checks the modified properties, as explained in this article:

     public class EntityUpdateEventListener
     	implements FlushEntityEventListener {
      
     	@Override
     	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();
     				root.setCreatedDate(new Date());
     			}
     		}
     	}
      
     	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;
     	}
     }
0 Likes

#3

Can @UpdateTimestamp also be used?

0 Likes

#4

That applies to any entity modification, not to specific entity attributes.

0 Likes