简体   繁体   中英

JPA Auditing LastModifiedBy/LastModifiedDate are null when being accessed in the transaction method

I have my auditing set up as shown below, and they work fine. The problem is when I want to access them within the transactional method before the update, the update id/date are always null and I'm not sure why.

@CreatedBy
@Column(name = "CREATE_ID", updatable = false, nullable = false)
private String createId;

@LastModifiedBy
@Column(name = "UPDATE_ID", nullable = false)
private String updateId;

@CreatedDate
@Column(name = "CREATE_DATE", updatable = false, nullable = false)
private Date createDate;

@LastModifiedDate
@Column(name = "UPDATE_DATE", nullable = false)
private Date updateDate;

The create/update methods that are calling save.

Note: BOTH of these work fine, creating/updating records in the database with the correct create/update audit values. The issue is that I cannot access update id/date within the update method and I'm not sure why/how to fix it.

@Override
@Transactional
public MyObj create(MyObj myObj) {
    MyObj createdMyObj = myObjRepo.save(myObj);
    System.out.println(createdMyObj.getCreateId()); // This works fine
    return createdMyObj;
}

@Override
@Transactional
public MyObj update(MyObj myObj) {
    MyObj updatedMyObj = myObjRepo.save(myObj);
    System.out.println(updatedMyObj.getUpdateId()); // This is null
    return updatedMyObj;
}

The auditing feature of Spring Data JPA is based on JPA lifecycle events and the event PreUpdate used to set the last-modified columns are only triggered when the JPA implementation actually updates the database which is in many cases at the end of the transaction.

See section 3.5.3 of the JPA specification :

The PreUpdate and PostUpdate callbacks occur before and after the database update operations to entity data respectively. These database operations may occur at the time the entity state is updated or they may occur at the time state is flushed to the database (which may be at the end of the transaction).

Therefore, if you want these values to be set you need to flush the persistence context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM