从Spring Data JPA的@LastModifiedDate中排除某些字段。

huangapple go评论69阅读模式
英文:

Exclude some fields from audit with Spring Data JPA @LastModifiedDate

问题

我有一个名为User的实体。这个实体包含了几个字段,其中一个是lastModifiedDate

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

每次表格被更新时,这个字段也会被更新。从本质上讲,这是可以的。
问题是,在同一个实体中,我还有另一个名为loginTime的字段:

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

每当新用户登录应用程序时,这个字段会被更新。
然而,当用户登录时,由于loginTime字段被更新,字段lastModifiedDate也会随之更新。
是否有办法阻止特定字段(比如loginTime)更新时导致lastModifiedDate被更新?

谢谢

英文:

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

得分: 1

你可以使用带有 @Query 注解的 JPQL 更新查询来更新仅 loginTime 字段,这样 lastModifiedDate 字段将不会被更新。

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

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

huangapple
  • 本文由 发表于 2020年8月20日 02:03:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63492606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定