我可以在接口上注释@EntityListener 吗?

Can I annotate @EntityListener on interfaces?

我正在设计数据库和实体。我需要为某些实体定义共享生命周期操作。

我可以在接口上注释 @EntityListeners 以便实现该接口的实体影响吗?

@EntityListeners({StorageObjectOwnerListener.class})
public interface StorageObjectOwner {
}

public class StorageOwnerOwnerListener {

    @PreRemove
    private void onPreRemove(final Object object) {
    }
}

现在任何实体工具都会受到影响。

public class MyEntity implements StorageObjectOwner {
    // will StorageObjectOwnerListener take action?
}

请点击下方link

Annotations on Interfaces?

希望能回答你的问题。我相信你应该使用 Spring 来注释接口,其中注释应该应用于所有 subclasses.For 例如,假设你有一个服务接口并且你可能有多个实现接口,但您希望应用安全注释而不考虑注释。在这种情况下,注释接口是最有意义的。

我已经用 JPA 2.1 试过了。可悲的是,它似乎只适用于实体。所以如果你的想法是使用一个接口,甚至是一个不是实体的超类,它是行不通的。

Specification 说:

When annotations are used, one or more entity listener classes are denoted using the EntityListeners annotation on the entity class or mapped superclass.

但是您可以使用默认侦听器(在 XML 配置中设置)。这样它会触发任何被移除的对象。您必须使用 object instanceof StorageObjectOwner.

过滤它们