5

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

Shaunyl
  • 527
  • 2
  • 11
  • 24
  • 1
    Not unless you rewrite the JPA listener that is involved in that and provide a way to exclude fields from there. From a JPA point-of-view the entity did change so what is wrong with that? It might be easier to move the `loginTime` to a new entity without a lastmodifieddate (just stick it into an table which keeps the login entires for instance). – M. Deinum Aug 19 '20 at 18:10
  • The default behavior is the right behavior actually, still you want you can use `@PreUpdate` instead `@LastModifiedDate` and conditionally update Ex : https://stackoverflow.com/a/27549023/4207306 – Eklavya Aug 19 '20 at 18:16
  • @User-Upvotedon'tsayThanks in PreUpdate methods I have not access to the old and the new version. so I should implement logic in setters for each property. Not feasible. – Shaunyl Aug 19 '20 at 18:20
  • I don't say you need to compare new to old, as you know early when you just want to update `loginTime` so restrict only that case either update. – Eklavya Aug 19 '20 at 18:24

1 Answers1

1

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);
Eklavya
  • 17,618
  • 4
  • 28
  • 57