在特定情况下防止AuditingEntityListener的默认行为

时间:2017-07-26 14:02:02

标签: java spring hibernate jpa spring-data

我使用AuditingEntityListener和注释@ CreatedDate 和@ LastModifiedDate 来管理创建/修改日期:

//...
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
//...

@Column(name = "creation_time", nullable = false)
@CreatedDate
private LocalDateTime creationDate;

@Column(name = "modification_time", nullable = false)
@LastModifiedDate
private LocalDateTime modificationDate;

但是,有时我希望能够在不修改creationDate和modificationDate字段的情况下修改此实体。有没有办法实现这个?

1 个答案:

答案 0 :(得分:1)

只需使用对应的列属性:

@Column(name = "creation_time", nullable = false, updatable = false)
@CreatedDate
private LocalDateTime creationDate;

@Column(name = "modification_time", nullable = false, insertable = false)
@LastModifiedDate
private LocalDateTime modificationDate;

我认为您的问题不在于AuditingEntityListener

如果您有兴趣以自己的方式管理modificationDate,则不应在@LastModifiedDate字段附近使用modificationDate注释,并为简单字段实施特殊规则:

@Column(name = "modification_time", nullable = false)
private LocalDateTime modificationDate;