可以在實體物件定義時實作Lifecycle介面,這個介面定義如下:
package org.hibernate.classic;
import java.io.Serializable;
import org.hibernate.CallbackException;
import org.hibernate.Session;
public interface Lifecycle {
public static final boolean VETO = true;
public static final boolean NO_VETO = false;
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);
}
import java.io.Serializable;
import org.hibernate.CallbackException;
import org.hibernate.Session;
public interface Lifecycle {
public static final boolean VETO = true;
public static final boolean NO_VETO = false;
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);
}
當物件實作Lifecycle介面時,會在save()、update()、delete()、load()等方法執行之前呼叫對應的onSave()、 onUpdate()、onDelete()與onLoad(),其中onSave()、onUpdate()、onDelete()與onLoad() 若傳回true或丟出CallbackException,則對應的操作中止。
可以在實體物件定義時實作Validatable介面,其定義如下:
package org.hibernate.classic;
public interface Validatable {
public void validate() throws ValidationFailure;
}
public interface Validatable {
public void validate() throws ValidationFailure;
}
如果定義時實作了Validatable介面,當物件被持久化之前會呼叫validate()方法,如果丟出ValidationFailure,則驗證 失敗,物件的資料不會儲存至資料庫中。