Exclude some fields from audit with Spring Data JPA @LastModifiedDate

Viewed 1376

I have an entity called User. This entity contains several fields and one of them is lastModifiedDate:

@LastModifiedDate
@Column(name = "last_modified_date", columnDefinition = "DATETIME")
private ZonedDateTime lastModifiedDate;

Every time the table is updated, this field gets updated too. Which per se is fine. The issue is that in the same entity I have also another field called loginTime:

@Column(name = "login_time", columnDefinition = "DATETIME")
private ZonedDateTime loginTime;

This field is updated whenever a new user logs into the application. However, when users log in, since the loginTime field is updated, the field lastModifiedDate is also updated consequently. Is there a way to prevent lastModifiedDate from being updated when specific fields (like loginTime) are updated?

Thank you

1 Answers

You can use JPQL update query using @Query to update only loginTime field then lastModifiedDate field will not be updated.

  @Modifying
  @Query("update User u set u.loginTime = :loginTime where u.id = :id")
  int updateLoginTime(@Param("loginTime") ZonedDateTime loginTime, @Param("id") Integer id);
Related