Does @EntityListener works with @MappedSuperclass as well?

余生颓废 提交于 2020-01-24 03:39:08

问题


Folks!

If I define an Entity Class and annotate it with @MappedSuperclass and an @EntityListener, does the listener also get called for lifecycle events within a child class?

Example:

@MappedSuperclass
@EntityListeners(class=LastUpdateListener.class)
public abstract class Animal {
    @Id private Integer id;
    private String name;
    private Calendar dateOfBirth;
    @Transient private int age;
    private Date lastUpdate;
    //getters and setters

    /**
     * Set my transient property at load time based on a calculation,
     * note that a native Hibernate formula mapping is better for this purpose.
     */
    @PostLoad
    public void calculateAge() {
        Calendar birth = new GregorianCalendar();
        birth.setTime(dateOfBirth);
        Calendar now = new GregorianCalendar();
        now.setTime( new Date() );
        int adjust = 0;
        if ( now.get(Calendar.DAY_OF_YEAR) - birth.get(Calendar.DAY_OF_YEAR) < 0) {
            adjust = -1;
        }
        age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + adjust;
    }
}

public class LastUpdateListener {
    /**
     * automatic property set before any database persistence
     */
    @PreUpdate
    @PrePersist
    public void setLastUpdate(Cat o) {
        o.setLastUpdate( new Date() );
    }
}

Thanks.


回答1:


Yes, method annotated with @PostLoad in mapped superclass and LastUpdateListener's entity listener methods get called.

Such a thing as lifecycle event for mapped superclass itself does not even exist. As usual, it applies to subclass.



来源:https://stackoverflow.com/questions/7936917/does-entitylistener-works-with-mappedsuperclass-as-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!