【问题标题】:JPA @PrePersist @PreUpdate in interface接口中的 JPA @PrePersist @PreUpdate
【发布时间】:2018-10-11 13:23:21
【问题描述】:

我想在接口中使用默认方法的 Java 8 特性,在我的实体中自动设置创建和 lastModified 日期。

我找到了实现使用@PrePersist @PreUpdate 注释的方法并在其中设置值的技巧。

但在保存实现接口的类的实例时,不会触发该方法。

我尝试通过向类中添加另一个方法来调用接口中的方法,这很有效。

我现在的问题是,如果这是预期行为,@PrePersist @PreUpdate 在接口中不起作用。

已经谢谢了。

【问题讨论】:

    标签: jpa


    【解决方案1】:

    我们可以在 JPA 的文档中看到

    /**
     * Is used to specify callback methods for the corresponding
     * lifecycle event. This annotation may be applied to methods
     * of an entity class, a mapped superclass, or a callback
     * listener class.
     *
     * @since Java Persistence 1.0
     */
    @Target({METHOD})
    @Retention(RUNTIME)
    public @interface PrePersist {
    }
    

    “实体类、映射超类或回调”其中接口不是这些。

    接口不能应用来改变实体结构或生命周期。我不知道你的具体情况,但你可能想考虑模板方法模式或重新考虑你的类的层次结构。

    【讨论】:

    • 感谢您提供的信息。那我就换超级班了。情况是,我不想为多个实体创建一个超类,这些实体并不真正相关,但都应该有一个 createdAt 和一个 lastModified 日期。
    猜你喜欢
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多