gpt4 book ai didi

hibernate - @EntityListener 是否也适用于 @MappedSuperclass?

转载 作者:行者123 更新时间:2023-12-04 15:36:28 28 4
gpt4 key购买 nike

伙计们!

如果我定义一个实体类并用 @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() );
}
}

谢谢。

最佳答案

是的,在映射的父类(super class)中用 @PostLoad 注释的方法和 LastUpdateListener 的实体监听器方法被调用。

映射父类(super class)本身的生命周期事件这样的事情甚至不存在。像往常一样,它适用于子类。

关于hibernate - @EntityListener 是否也适用于 @MappedSuperclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7936917/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com