Callback methods
和Entity Listeners
是Hibernate特別有用的特性,有時候會帶來很多意想不到的功效哦!所以這里花點時間整理一下關于Callback methods
和Entity Listeners
的特性和使用方法,供大家查閱。
Callback methods
顧名思義:“回調方法”,作用在Entity類中,結合@Entity
。Hibernate支持通過注解和xml的方式輕松對Entity定義回調方法,個性化數據的增刪改查。
Hibernate支持的回調注解
@PrePersist
Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
在數據持久化到數據庫之前執行
@PreRemove
Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
執行數據刪除之前調用
@PostPersist
Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
在執行數據插入之后調用
@PostRemove
Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
在執行數據刪除之后調用
@PreUpdate
Executed before the database UPDATE operation.
在執行數據更新之前調用
@PostUpdate
Executed after the database UPDATE operation.
在執行數據更新之后調用
@PostLoad
Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.
在數據從數據庫加載并且賦值到當前對象后調用
使用場景
假設我們持久化的Entity都需要保存createdTime
字段。這個字段比較特殊,在保存數據之前獲取當前時間,賦值并保存。
傳統的做法:
entity.setCreatedTime(new Date());
entityDao.save(entity);
使用Callback methods的做法
在創建entity的model類中使用@PrePersist
,因為我們是在保存數據庫之前給其賦值
@Entity(...)
public class EntityModel{
...
private Date createdTime;
@PrePersist
protected void onCreate() {
createdTime= new Date();
}
}
這樣我們在業務處理的時候,只需處理業務相關的屬性就可以了!
其他回調方法的用法類似,根據場景選擇不同的回調就可以了。
關于EntityListeners
上面介紹了Callback methods
,EntityListeners
其實是定義了多個Callback methods。
接上面的示例,加入我們定義的所有的Entity都要保存createdTime
屬性,那么就可以定義一個EntityListener(一個Entity支持多個EntityListener的定義),將回調方法定義在其中,然后將Listener指定給Entity即可。
示例:
首先我們定義一個名為CreatedTimePersistentListener
的類
public class CreatedTimePersistentListener{
@PrePersist
protected void onCreate(Object object) {
try {
BeanUtils.setProperty(object, "createdTime", new Date());
}cache(Exception e){
//....
}
}
}
使用apache的BeanUtils
工具類,通過反射的方式,將createdTime
屬性賦值給object
對象。(object對象必須包含createdTime
屬性)
然后通過@EntityListeners
注解,作用給指定的Entity
@EntityListeners({CreatedTimePersistentListener.class})
public class EntityModel{
}
只要加了@EntityListeners({CreatedTimePersistentListener.class})
的Entity都會默認在保存數據之前執行createdTime
的賦值。
綜合來說,“Callback methods”和“Entity listeners” 使用方法很簡單,卻非常有用,使我們的代碼更容易組織和維護!