Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
}
like image 366
Jin Kwon Avatar asked Feb 04 '26 02:02

Jin Kwon


1 Answers

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.

like image 193
Vlasec Avatar answered Feb 05 '26 15:02

Vlasec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!