JPA内部回调方法 内部回调方法是在实体类中定义的方法。例如,下面的实体类定义了所有支持的回调方法空的实现:
@Entity
public static class MyEntityWithCallbacks {
@PrePersist void onPrePersist() {}
@PostPersist void onPostPersist() {}
@PostLoad void onPostLoad() {}
@PreUpdate void onPreUpdate() {}
@PostUpdate void onPostUpdate() {}
@PreRemove void onPreRemove() {}
@PostRemove void onPostRemove() {}
}
内部回调方法应该总是返回void,并且没有参数。他们可以有任何名称和任何访问级别(公共,受保护,包和私有),但不应该是静态的。
的注释指定时调用的回调方法:
@PrePersist - before a new entity is persisted (added to the EntityManager).
@PostPersist - after storing a new entity in the database (during commit or flush).
@PostLoad - after an entity has been retrieved from the database.
@PreUpdate - when an entity is identified as modified by the EntityManager.
@PostUpdate - after updating an entity in the database (during commit or flush).
@PreRemove - when an entity is marked for removal in the EntityManager.
@PostRemove - after deleting an entity from the database (during commit or flush).
实体类可以包括用于任何子集或生命周期事件的组合,但没有为同一事件多于一个回调方法回调方法。但是,通过用多个注释标记多个回调事件,可以使用同一方法。
默认情况下,还会为子类的实体对象调用超类实体类中的回调方法,除非该子类重写该回调方法。
实施限制 为避免触发实体生命周期事件(仍在进行中)的原始数据库操作发生冲突,回调方法不应调用EntityManager或Query方法,也不应访问任何其他实体对象。
如果回调方法在活动事务中抛出异常,则事务被标记为回滚,并且不会为该操作调用更多回调方法。
嘿。当我测试时,我发现监听器中的所有操作都在主操作的同一事务中。我使用@PostUpdate注释来标记侦听器。 – Scarlett 2012-04-12 07:01:23