接口中的JPA @PrePersist @PreUpdate

时间:2018-10-11 13:23:22

标签: jpa

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

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

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

我通过在类中添加另一个方法来进行尝试,该方法在接口中调用了该方法,并且有效。

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

已经感谢。

1 个答案:

答案 0 :(得分:0)

我们可以阅读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 {
}

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

不能使用界面来更改实体结构或生命周期。我不知道您的具体情况,但您可能想考虑使用“模板方法”模式或重新考虑类的层次结构。

相关问题