Home > database >  Update of Date fields from Parent class not working in Spring Data Jpa
Update of Date fields from Parent class not working in Spring Data Jpa

Time:10-10

I am using Spring Boot and Spring Data JPA and wanted to update the LastUpdatedDate and LastModifiedBy fields in JPA update statement. Assume Employee is my entity class which extends AbstractBaseEntity class.

@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;
}

Another class

public class Employee extends AbstractBaseEntity{
   ...
   ...
   ...    
}

Below query not updating any date. How can we fix it?

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

CodePudding user response:

In order to make auditing work at all, please insure @EnableJpaAuditing annotation added to @Configuration class.

The AuditingEntityListener methods are called in the @PrePersist and @PreUpdate phase. AFAIK is works only if you directly manipulate entities. It doesn't work if you use @Query statements.

Update statement must do it manually, for example:

UPDATE Employee p SET p.status =:status, p.lastUpdatedOn = 
:lastUpdatedOn, p.lastUpdatedBy = :lastUpdatedBy WHERE 
p.srcProjectKeyId = (:id)

To get the current date use:

Date now = new Date();
// or
long now = System.currentTimeMillis();

To get the current user (a.k.a. principal) use:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

Here are longer discussions about cache invalidation issues:

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

  • Related