在Hibernate中,有两种方式可以捕获实体对象的GRUD操作并执行相应的处理
Hibernate回调(org.hibernate.classic.Lifecycle接口):
//Provides callbacks from the Session to the persistent object.
//Persistent classes may implement this interface but they are not
//required to.
//If a CallbackException is thrown, the operation is vetoed and the
//exception is passed back to the application.
public interface Lifecycle {
//If onSave(), onUpdate() or onDelete() return VETO,
//the operation is silently vetoed.
public static final boolean VETO = true;
public static final boolean NO_VETO = false;
//Called just before the object is saved
public boolean onSave(Session s) throws CallbackException;
//Called when an entity is passed to Session.update().
//This method is not called every time the object's
//state is persisted during a flush.
public boolean onUpdate(Session s) throws CallbackException;
//Called just before an object is deleted
public boolean onDelete(Session s) throws CallbackException;
//Called just after an object is loaded
public void onLoad(Session s, Serializable id);
}
需要注意的地方:
1,如果onSave()、onUpdate()、onDelete()方法返回VOTE(true)或者在以上方法中抛出了CallbackException异常,操作将会停止而不会调用之后的Session.save()、Session.update()、Session.delete()方法
2,并不是每次调用Session.update()方法之前都会调用onUpdate()方法
3,调用Session.get()方法会直接返回实体对象,故在调用该方法后会立即调用onload()方法,而调用Session.load()方法返回的是实体对象的代理,故在调用该方法后不会立即调用onload()方法