3

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?
}
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • @NeilStockton I wouldn't post this kind of question if I won't care about any implementation specific behaviour. What a classic comment. – Jin Kwon Aug 02 '16 at 07:08

1 Answers1

3

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.

Vlasec
  • 5,500
  • 3
  • 27
  • 30