注册监听器:
MyPreInsertListener.java:
- package eventListener;
- import org.hibernate.event.PreInsertEvent;
- import org.hibernate.event.PreInsertEventListener;
- import basicCar.bean.Account;
- public class MyPreInsertListener implements PreInsertEventListener {
- public boolean onPreInsert(PreInsertEvent event) {
- Object ob = event.getEntity();
- if (ob instanceof Account) {
- Account bc = (Account) ob;
- if (bc.getOpendate() == null)
- System.out
- .println("the date value is null, i won't insert this!!");
- return true;
- }
- return false;
- }
- }
- package eventListener;
- import org.hibernate.HibernateException;
- import org.hibernate.event.LoadEvent;
- import org.hibernate.event.LoadEventListener;
- import org.hibernate.event.def.DefaultLoadEventListener;
- import basicCar.bean.Account;
- public class MyLoadListener extends DefaultLoadEventListener {
- public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType)
- throws HibernateException {
- System.out.println("entityName:" + event.getEntityClassName()+" id: "+event.getEntityId());
- super.onLoad(event, loadType);
- if (event.getEntityClassName().equals("basicCar.bean")) {
- Account bc = (Account) event.getResult();
- if (bc != null && bc.getOpendate()== null) {
- System.out.println("自定义的load事件: 没有日期,不要");
- throw new HibernateException("自定义的load事件: 实体没有日期,抛出异常");
- }
- }
- }
- }
下面的代码为load和pre-insert事件注册了两个监听器:
- MyLoadListener mll = new MyLoadListener();
- MyPreInsertListener mpl = new MyPreInsertListener();
- cfg.setListener("load", mll);
- cfg.setListener("pre-inset",mpl);
下面是为某个事件注册多个监听器的方法:
- LoadEventListener[] stack = {new MyLoadListener(),new DefaultLoadEventListener()};
- cfg.setListener("load", stack);
拦截器:
1.日志记录拦截器:
session范围的:
- void saveEntity() {
- Session session;
- session = sf.openSession(new LogInterceptor());
- 2 Nov 2012 02:15:33 GMT: save name: basicCar.bean.Account id: 56
- 2 Nov 2012 02:15:33 GMT: save name: basicCar.bean.Account id: 57
- 2 Nov 2012 02:15:33 GMT : update name: basicCar.bean.Customer id: 299
- creations:2,Updates:1,Loads:14
sessinfactory范围的:
使用这个sessionfactory所建立的所有sessin都将使用这个拦截器
- void DoConfiguration() {
- // new a configuration and read the configuration from the given path
- cfg = new Configuration();
- cfg.configure("/basicCar/hibernate.cfg.xml");
- // use the properites in the configure file to new a sessionFactory
- sf = cfg.setInterceptor(new LogInterceptor()).buildSessionFactory();
- }
复合拦截器:
LogInterceptor.java:
- package interceptor;
- import java.io.Serializable;
- import java.util.Date;
- import org.hibernate.CallbackException;
- import org.hibernate.EmptyInterceptor;
- import org.hibernate.Transaction;
- import org.hibernate.type.Type;
- import basicCar.bean.Customer;
- public class LogInterceptor extends EmptyInterceptor {
- private int updates;
- private int creates;
- private int loads;
- public void onDelete(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) {
- Date d = new Date(System.currentTimeMillis());
- String content = d.toGMTString() + ": delete name: "
- + entity.getClass().getName() + " id: " + id;
- FileLog fl = new FileLog(content);
- }
- public boolean onFlushDirty(Object entity, Serializable id,
- Object[] currentState, Object[] previousState,
- String[] propertyNames, Type[] types) {
- System.err.println("!!! some dirty !!!");
- updates++;
- Date d = new Date(System.currentTimeMillis());
- String content = d.toGMTString() + " : update name: "
- + entity.getClass().getName() + " id: " + id;
- FileLog fl = new FileLog(content);
- for (int i = 0; i < propertyNames.length; i++) {
- System.out.println(propertyNames[i] + ": " + previousState[i]
- + "; " + currentState[i]);
- }
- System.out.println("??true??n or false ");
- return false;
- }
- public boolean onLoad(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) {
- loads++;
- return true;
- }
- public boolean onSave(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) {
- System.out.println("onsave2");
- creates++;
- Date d = new Date(System.currentTimeMillis());
- String content = d.toGMTString() + ": save name: "
- + entity.getClass().getName() + " id: " + id;
- FileLog fl = new FileLog(content);
- /*if (entity instanceof BasicCar) {
- for (int i = 0; i < propertyNames.length; i++) {
- if ("date".equals(propertyNames[i])&&state[i]!=null) {
- System.out.println(propertyNames[i] + ":statenull " + state[i]);
- state[i] = new Date(System.currentTimeMillis());
- return true;
- }
- }
- }*/
- if (entity instanceof Customer) {
- for (int i = 0; i < propertyNames.length; i++) {
- if ("salesname".equals(propertyNames[i])) {
- System.out.println(propertyNames[i] + ":salesname!!@@ " + state[i]);
- state[i] = "PPPPPP";
- return true;
- }
- }
- }
- System.out.println();
- return false;
- }
- public void afterTransactionCompletion(Transaction tx) {
- if (tx.wasCommitted()) {
- String content = "creations:" + creates + ",Updates:" + updates
- + ",Loads:" + loads;
- System.out.println("creations:" + creates + ",Updates:" + updates
- + ",Loads:" + loads);
- FileLog fl = new FileLog(content);
- }
- updates = 0;
- creates = 0;
- loads = 0;
- }
- public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException
- {
- System.out.println("collection!!!!!!!!"+collection.getClass().getName());
- }
- public String onPrepareStatement(String arg0) {
- String sqlString=arg0;
- // System.out.println("log "+sqlString);
- return sqlString;
- }
- public String getEntityName(Object arg0) throws CallbackException {
- return null;
- }
- }
MyInterceptor.java:
- package interceptor;
- import java.io.Serializable;
- import java.sql.Date;
- import org.hibernate.CallbackException;
- import org.hibernate.EmptyInterceptor;
- import org.hibernate.type.Type;
- import basicCar.bean.Account;
- public class MyInterceptor extends EmptyInterceptor {
- public boolean onSave(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) {
- System.out.println("onsave");
- if (entity instanceof Account) {
- for (int i = 0; i < propertyNames.length; i++) {
- if ("date".equals(propertyNames[i])&&state[i]!=null) {
- System.out.println(propertyNames[i] + ":::" + state[i]);
- state[i] = new Date(System.currentTimeMillis());
- System.out.println(propertyNames[i] + ":##::" + state[i]);
- return true;
- }
- }
- }
- return false;
- }
- public String onPrepareStatement(String arg0) {
- String sqlString=arg0;
- // System.out.println("my "+sqlString);
- return sqlString;
- }
- public String getEntityName(Object arg0) throws CallbackException {
- return null;
- }
- }
ChainedInterceptor.java:
- package interceptor;
- import java.io.Serializable;
- import java.util.Iterator;
- import org.hibernate.CallbackException;
- import org.hibernate.EntityMode;
- import org.hibernate.Interceptor;
- import org.hibernate.Transaction;
- import org.hibernate.type.Type;
- /**
- * Implementation of the Hibernate <code>Interceptor</code> interface that
- * allows the chaining of several different instances of the same interface.
- *
- * @author Laurent RIEU
- * @see Interceptor
- */
- public class ChainedInterceptor implements Interceptor {
- // Interceptors to be chained
- private Interceptor[] interceptors;
- public ChainedInterceptor() {
- super();
- }
- public ChainedInterceptor(Interceptor[] interceptors) {
- super();
- this.interceptors = interceptors;
- }
- public boolean onLoad(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) throws CallbackException {
- boolean result = false;
- for (int i = 0; i < interceptors.length; i++) {
- if (interceptors[i].onLoad(entity, id, state, propertyNames, types)) {
- result = true;
- }
- }
- return result;
- }
- public boolean onFlushDirty(Object entity, Serializable id,
- Object[] currentState, Object[] previousState,
- String[] propertyNames, Type[] types) throws CallbackException {
- boolean result = false;
- for (int i = 0; i < interceptors.length; i++) {
- if (interceptors[i].onFlushDirty(entity, id, currentState,
- previousState, propertyNames, types)) {
- result = true;
- }
- }
- return result;
- }
- public boolean onSave(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) throws CallbackException {
- System.out.println("onsave3");
- boolean result = false;
- for (int i = 0; i < interceptors.length; i++) {
- if (interceptors[i].onSave(entity, id, state, propertyNames, types)) {
- result = true;
- }
- }
- return result;
- }
- public void onDelete(Object entity, Serializable id, Object[] state,
- String[] propertyNames, Type[] types) throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].onDelete(entity, id, state, propertyNames, types);
- }
- }
- public void preFlush(Iterator entities) throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].preFlush(entities);
- }
- }
- public void postFlush(Iterator entities) throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].postFlush(entities);
- }
- }
- public Boolean isTransient(Object entity) {
- Boolean result = false;
- for (int i = 0; i < interceptors.length; i++) {
- result = interceptors[i].isTransient(entity);
- if (result != null) {
- result=true;
- }
- }
- return result;
- }
- static int l = 0;
- public int[] findDirty(Object entity, Serializable id,
- Object[] currentState, Object[] previousState,
- String[] propertyNames, Type[] types) {
- //这里必须初始化为空,否则其内里interceptor的任何改变都会被改回去
- int[] result = {};
- boolean someDirty = onFlushDirty(entity, id, currentState,
- previousState, propertyNames, types);
- if (someDirty == false)
- return result;
- if (l < interceptors.length) {
- result = interceptors[l].findDirty(entity, id, currentState,
- previousState, propertyNames, types);
- l++;
- return result;
- }
- l = 0;
- return result;
- }
- static int m = 0;
- public Object instantiate(String entityName, EntityMode entityMode,
- Serializable id) throws CallbackException {
- Object result = null;
- if (m < interceptors.length) {
- result = interceptors[m].instantiate(entityName, entityMode, id);
- m++;
- return result;
- }
- m = 0;
- return result;
- }
- public Interceptor[] getInterceptors() {
- return interceptors;
- }
- public void setInterceptors(Interceptor[] interceptors) {
- this.interceptors = interceptors;
- }
- public void afterTransactionBegin(Transaction arg0) {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].afterTransactionBegin(arg0);
- }
- }
- public void afterTransactionCompletion(Transaction arg0) {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].afterTransactionCompletion(arg0);
- }
- }
- public void beforeTransactionCompletion(Transaction arg0) {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].beforeTransactionCompletion(arg0);
- }
- }
- static int n = 0;
- public Object getEntity(String arg0, Serializable arg1)
- throws CallbackException {
- Object entity = null;
- if (n < interceptors.length) {
- entity = interceptors[n].getEntity(arg0, arg1);
- n++;
- return entity;
- }
- n = 0;
- return entity;
- }
- static int i = 0;
- public String getEntityName(Object arg0) throws CallbackException {
- String entityName = null;
- if(i < interceptors.length) {
- entityName = interceptors[i].getEntityName(arg0);
- i++;
- return entityName;
- }
- i=0;
- return entityName;
- }
- public void onCollectionRecreate(Object arg0, Serializable arg1)
- throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].onCollectionRecreate(arg0, arg1);
- }
- }
- public void onCollectionRemove(Object arg0, Serializable arg1)
- throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].onCollectionRemove(arg0, arg1);
- }
- }
- public void onCollectionUpdate(Object arg0, Serializable arg1)
- throws CallbackException {
- for (int i = 0; i < interceptors.length; i++) {
- interceptors[i].onCollectionUpdate(arg0, arg1);
- }
- }
- static int k = 0;
- public String onPrepareStatement(String arg0) {
- String sqlString = arg0;
- if (k < interceptors.length) {
- sqlString = interceptors[k].onPrepareStatement(sqlString);
- k++;
- return sqlString;
- }
- System.out.println("kkk != null " + k + " " + sqlString);
- k = 0;
- return sqlString;
- }
- }