[英]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. 问题是,当我想在更新之前在事务方法中访问它们时,更新ID /日期始终为null,我不确定为什么。
@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. 问题是我无法在更新方法中访问更新ID /日期,而且不确定为什么/如何解决它。
@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. Spring Data JPA的审计功能基于JPA生命周期事件, 而用于设置最后修改的列的PreUpdate
事件仅在JPA实现实际更新数据库时才触发,而在许多情况下,这是在事务结束时进行的。
See section 3.5.3 of the JPA specification : 参见JPA规范的第3.5.3节:
The PreUpdate and PostUpdate callbacks occur before and after the database update operations to entity data respectively. PreUpdate和PostUpdate回调分别发生在对实体数据进行数据库更新操作之前和之后。 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. 因此,如果要设置这些值,则需要刷新持久性上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.