Hibernate的Lifecycle Validatable 和 Interceptor

Lifecycle接口包含4个方法:

public boolean onSave(Session s) throws CallbackException;
public boolean onUpdate(Session s) throws CallbackException;
public boolean onDelete(Session s) throws CallbackException;
public void onLoad(Session s, Serializable id);

当在实现了该接口的Entity Class的Object上发生save()等事件时,会先调用相应的on方法,若返回[color=red]true[/color]或抛CallbackException时操作中止.[color=red]onLoad()方法在Object加载之后触发[/color].
Validatable接口包含1个方法:
public void validate() throws ValidationFailure
,该方法在Object持久化之前调用,用于验证数据的正确性.
Interceptor接口用于取代上面2个接口:当pojo实现了接口之后,就不再是pojo,从而可能产生可移植的问题,hibernate提供Interceptor接口解决这个问题.Interceptor接口由具体的interceptor实现,并注入session使用.接口方法如下:
// 載入物件之前執行
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;

// flush 時,如果發現有Dirty data,則執行此方法
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException;

// 儲存物件前執行
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;

// 刪除物件前執行
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;

// 在 flush 前執行
public void preFlush(Iterator entities) throws CallbackException;

// 在 flush 後執行
public void postFlush(Iterator entities) throws CallbackException;

// 判斷傳入的物件是否為 transient 狀態
public Boolean isTransient(Object entity);

// flush 前呼叫這個方法判斷 Dirty data
// 傳回Dirty data屬性索引或null採預設行為
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types);

// 手動建立實體物件,如果傳回 null,則使用預設的建構方法建立實例
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;

// 傳回實體名稱
public String getEntityName(Object object) throws CallbackException;

// 取得實體物件
public Object getEntity(String entityName, Serializable id) throws CallbackException;

// beginTransaction() 之後執行
public void afterTransactionBegin(Transaction tx);

// 在事務完成前執行
public void beforeTransactionCompletion(Transaction tx);

// 在事務完成後執行
public void afterTransactionCompletion(Transaction tx);

Interceptor的使用:
SessionFactory.openSession(Interceptor)//每个session拥有自己的拦截器,不共享
Configuration.setInterceptor(Interceptor)//各个session共享此拦截器


参考文章:http://caterpillar.onlyfun.net/Gossip/HibernateGossip/Interceptor.html
http://blog.csdn.net/javacoffe/archive/2007/07/24/1705173.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值