【问题标题】:Update of Date fields from Parent class not working in Spring Data Jpa从父类更新日期字段在 Spring Data Jpa 中不起作用
【发布时间】:2021-11-29 09:03:48
【问题描述】:

我正在使用 Spring Boot 和 Spring Data JPA,并希望更新 JPA 更新语句中的 LastUpdatedDateLastModifiedBy 字段。假设 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);

【问题讨论】:

    标签: jpa spring-data-jpa


    【解决方案1】:

    为了make auditing work at all,请确保@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 - Modifying update query - Refresh persistence context

    Spring Data JPA Update @Query not updating?

    Clear Hibernate 2nd level cache after manually DB update

    【讨论】:

    • 再见问题。 “clearAutomatically = true”实际上应该完成这项工作。是否有可能,您有二级缓存或一些并发问题?你怎么检查,日期没有更新???
    • 你能在这里指导我吗 - stackoverflow.com/questions/69512728/…
    猜你喜欢
    • 2018-01-02
    • 2019-05-18
    • 2015-05-25
    • 1970-01-01
    • 2018-07-05
    • 2017-09-21
    • 2019-03-02
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多