Search code examples
jpainterfaceentitylisteners

Can I annotate @EntityListener on interfaces?


I'm designing database and entities. I need to define shared lifecycle actions for some entities.

Can I annotate @EntityListeners on interfaces so that entities implementing the interface affects?

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

public class StorageOwnerOwnerListener {

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

Now any entity implements get affected.

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

Solution

  • I've tried that with JPA 2.1. Sadly, it only seems to work with entities. So if your idea is using an interface, or even a superclass that is not an entity, it won't work.

    Specification says:

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

    You could however use a default listener (set in XML configuration). That way it would trigger on any object being removed. You'd have to filter them with object instanceof StorageObjectOwner.