【问题标题】:Does @EntityListener works with @MappedSuperclass as well?@EntityListener 也可以与 @MappedSuperclass 一起使用吗?
【发布时间】:2011-12-17 17:24:45
【问题描述】:

伙计们!

如果我定义一个实体类并使用@MappedSuperclass@EntityListener 对其进行注释,是否还会调用侦听器来处理子类中的生命周期事件?

例子:

@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() );
    }
}

谢谢。

【问题讨论】:

    标签: hibernate jpa annotations entitylisteners


    【解决方案1】:

    是的,在映射的超类中使用 @PostLoad 注释的方法和 LastUpdateListener 的实体侦听器方法被调用。

    映射超类本身的生命周期事件之类的东西甚至不存在。像往常一样,它适用于子类。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2011-08-15
    • 2018-02-16
    • 2020-06-30
    • 2014-11-15
    • 2011-12-07
    • 2011-11-20
    相关资源
    最近更新 更多