JPA是否允许对MappedSuperclass中的嵌入式类进行PrePersist / PreUpdate?

时间:2019-06-28 16:50:01

标签: java jpa

我有一个@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规范允许吗?

0 个答案:

没有答案