我正在使用 Spring Boot 和 Spring Data JPA,并希望更新JPA 更新陳述句中的LastUpdatedDate和LastModifiedBy欄位。假設 Employee 是我的物體類,它擴展了AbstractBaseEntity類。
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Data
public abstract class AbstractBaseEntity {
@CreatedBy
@JsonIgnore
@Column(name = "CRTE_USER_ID")
protected String createdByUser = "TEST_USER";
@CreatedDate
@JsonIgnore
@Column(name = "CRTE_DT", updatable = false)
protected Date createdDate = new Date();
@LastModifiedBy
@JsonIgnore
@Column(name = "UPDT_USER_ID")
protected String lastUpdatedByUser = "TEST_USER";
@LastModifiedDate
@JsonIgnore
@Column(name = "UPDT_DT")
protected Date lastUpdatedOn = new Date();
@Version
@JsonIgnore
@Column(name = "VER_NUM")
protected Integer versionNumber = 1;
}
另一堂課
public class Employee extends AbstractBaseEntity{
...
...
...
}
下面的查詢不更新任何日期。我們該如何解決?
@Modifying(clearAutomatically = true)
@Transactional
@Query("UPDATE Employee p SET p.status =:status, p.lastUpdatedOn = :lastUpdatedOn WHERE p.srcProjectKeyId = (:id)")
int updatestatus(@Param("status") String status, @Param("id") Long id, @Param("lastUpdatedOn") Date lastUpdatedOn);
uj5u.com熱心網友回復:
為了使審計作業,請確保@EnableJpaAuditing在@Configuration類中添加注釋。
這些AuditingEntityListener方法在@PrePersist和@PreUpdate階段被呼叫。AFAIK 僅在您直接操作物體時才有效。如果您使用@Query陳述句,它將不起作用。
更新陳述句必須手動完成,例如:
UPDATE Employee p SET p.status =:status, p.lastUpdatedOn =
:lastUpdatedOn, p.lastUpdatedBy = :lastUpdatedBy WHERE
p.srcProjectKeyId = (:id)
要獲取當前日期,請使用:
Date now = new Date();
// or
long now = System.currentTimeMillis();
要獲取當前用戶(又名主體),請使用:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();
以下是有關快取失效問題的詳細討論:
Spring Boot Data JPA - 修改更新查詢 - 重繪 持久化背景關系
Spring Data JPA 更新 @Query 不更新?
手動更新資料庫后清除 Hibernate 二級快取
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318573.html
上一篇:更新表以包含影像
