@EntityListener 是否也适用于 @MappedSuperclass? [英] Does @EntityListener works with @MappedSuperclass as well?
本文介绍了@EntityListener 是否也适用于 @MappedSuperclass?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
伙计们!
如果我定义了一个实体类并使用 @MappedSuperclass
和一个 @EntityListener
对其进行注释,那么在子类中是否也会调用侦听器来处理生命周期事件?>
示例:
@MappedSuperclass@EntityListeners(class=LastUpdateListener.class)公共抽象类动物{@Id 私有整数 id;私有字符串名称;私人日历 dateOfBirth;@Transient 私有整数年龄;私人日期 lastUpdate;//getter 和 setter/*** 根据计算在加载时设置我的瞬态属性,* 请注意,本机 Hibernate 公式映射更适合此目的.*/@PostLoad公共无效计算年龄(){日历诞生 = new GregorianCalendar();出生时间(出生日期);现在日历 = new GregorianCalendar();now.setTime(新日期());int 调整 = 0;if ( now.get(Calendar.DAY_OF_YEAR) -birth.get(Calendar.DAY_OF_YEAR) <0) {调整 = -1;}age = now.get(Calendar.YEAR) -birth.get(Calendar.YEAR) + adjust;}}公共类 LastUpdateListener {/*** 在任何数据库持久化之前设置自动属性*/@预更新@PrePersist公共无效 setLastUpdate(Cat o) {o.setLastUpdate(new Date());}}
谢谢.
解决方案
是的,映射超类中用 @PostLoad 注释的方法和 LastUpdateListener 的实体侦听器方法被调用.
像映射超类本身的生命周期事件这样的事情甚至不存在.像往常一样,它适用于子类.
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.
解决方案
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.
这篇关于@EntityListener 是否也适用于 @MappedSuperclass?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文