我有一个@MappedSuperclass
,其中包含一个@Embedded
元素。在不使用@MappedSuperclass
的情况下,@PrePersist
和@PreUpdate
会按预期执行。
@MappedSuperclass
public abstract class BaseLocalizedString implements Serializable {
@Embedded
private final Audit audit = new Audit();
}
所以我的解决方法是添加@PrePersist
和@PreUpdate
/**
* Workaround since the Embedded PrePersist does not get called.
*/
@PrePersist
public void created() {
audit.setCreatedBy(AuditContext.getUserID());
audit.setCreatedByName(AuditContext.getUserFullName());
audit.setCreatedOn(ZonedDateTime.now());
audit.setLastUpdatedBy(AuditContext.getUserID());
audit.setLastUpdatedByName(AuditContext.getUserFullName());
audit.setLastUpdatedOn(ZonedDateTime.now());
}
/**
* Workaround since the Embedded PreUpdate does not get called.
*/
@PreUpdate
public void updated() {
audit.setLastUpdatedBy(AuditContext.getUserID());
audit.setLastUpdatedByName(AuditContext.getUserFullName());
audit.setLastUpdatedOn(ZonedDateTime.now());
}
审计
@Embeddable
@Data
public class Audit implements Serializable {
@Column(updatable = false, nullable = false)
private String createdBy;
@Column(updatable = false, nullable = false)
private String createdByName;
@Column(updatable = false, nullable = false)
private ZonedDateTime createdOn;
@Column(nullable = false)
private String lastUpdatedBy;
@Column(nullable = false)
private String lastUpdatedByName;
@Column(nullable = false)
private ZonedDateTime lastUpdatedOn;
@PrePersist
public void created() {
lastUpdatedBy = createdBy = AuditContext.getUserID();
lastUpdatedByName = createdByName = AuditContext.getUserFullName();
lastUpdatedOn = createdOn = ZonedDateTime.now();
}
@PreUpdate
public void updated() {
lastUpdatedBy = AuditContext.getUserID();
lastUpdatedByName = AuditContext.getUserFullName();
lastUpdatedOn = ZonedDateTime.now();
}
}
在Hibernate中,我发现它不允许在MappedSuperclass中的嵌入式类上执行PrePersist / PreUpdate。我的问题是JPA规范允许吗?