hibernate 拦截器和事件框架

注册监听器:

MyPreInsertListener.java:

[java]  view plain copy
  1. package eventListener;  
  2.   
  3. import org.hibernate.event.PreInsertEvent;  
  4. import org.hibernate.event.PreInsertEventListener;  
  5.   
  6. import basicCar.bean.Account;  
  7.   
  8.   
  9. public class MyPreInsertListener implements PreInsertEventListener {  
  10.   
  11.     public boolean onPreInsert(PreInsertEvent event) {  
  12.         Object ob = event.getEntity();  
  13.         if (ob instanceof Account) {  
  14.             Account bc = (Account) ob;  
  15.             if (bc.getOpendate() == null)  
  16.                 System.out  
  17.                         .println("the date value is null, i won't insert this!!");  
  18.             return true;  
  19.         }  
  20.         return false;  
  21.     }  
  22.   
  23. }  


MyLoadListener.java:

[java]  view plain copy
  1. package eventListener;  
  2.   
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.event.LoadEvent;  
  5. import org.hibernate.event.LoadEventListener;  
  6. import org.hibernate.event.def.DefaultLoadEventListener;  
  7.   
  8. import basicCar.bean.Account;  
  9.   
  10.   
  11.   
  12.   
  13. public class MyLoadListener extends DefaultLoadEventListener {  
  14.     public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType)  
  15.             throws HibernateException {  
  16.   
  17.         System.out.println("entityName:" + event.getEntityClassName()+"  id: "+event.getEntityId());  
  18.           
  19.         super.onLoad(event, loadType);  
  20.           
  21.         if (event.getEntityClassName().equals("basicCar.bean")) {  
  22.             Account bc = (Account) event.getResult();  
  23.             if (bc != null && bc.getOpendate()== null) {  
  24.                 System.out.println("自定义的load事件: 没有日期,不要");  
  25.                 throw new HibernateException("自定义的load事件: 实体没有日期,抛出异常");  
  26.             }  
  27.   
  28.         }  
  29.     }  
  30. }  



下面的代码为load和pre-insert事件注册了两个监听器:

[java]  view plain copy
  1. MyLoadListener mll = new MyLoadListener();  
  2.         MyPreInsertListener mpl = new MyPreInsertListener();  
  3.         cfg.setListener("load", mll);  
  4.         cfg.setListener("pre-inset",mpl);  

下面是为某个事件注册多个监听器的方法:

[java]  view plain copy
  1. LoadEventListener[] stack = {new MyLoadListener(),new DefaultLoadEventListener()};  
  2.         cfg.setListener("load", stack);  


拦截器:

1.日志记录拦截器:

session范围的:

[java]  view plain copy
  1. void saveEntity() {  
  2.           
  3.         Session session;  
  4.         session = sf.openSession(new LogInterceptor());  
myfile.dat:

[java]  view plain copy
  1. 2 Nov 2012 02:15:33 GMT: save  name: basicCar.bean.Account  id: 56  
  2. 2 Nov 2012 02:15:33 GMT: save  name: basicCar.bean.Account  id: 57  
  3. 2 Nov 2012 02:15:33 GMT : update name: basicCar.bean.Customer  id: 299  
  4. creations:2,Updates:1,Loads:14  



sessinfactory范围的:

使用这个sessionfactory所建立的所有sessin都将使用这个拦截器

[java]  view plain copy
  1. void DoConfiguration() {  
  2.         // new a configuration and read the configuration from the given path  
  3.         cfg = new Configuration();  
  4.         cfg.configure("/basicCar/hibernate.cfg.xml");  
  5.         // use the properites in the configure file to new a sessionFactory  
  6.         sf = cfg.setInterceptor(new LogInterceptor()).buildSessionFactory();  
  7.     }  
2.实现属性检查修改拦截器:



复合拦截器:

LogInterceptor.java:

[java]  view plain copy
  1. package interceptor;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Date;  
  5.   
  6. import org.hibernate.CallbackException;  
  7. import org.hibernate.EmptyInterceptor;  
  8. import org.hibernate.Transaction;  
  9. import org.hibernate.type.Type;  
  10.   
  11. import basicCar.bean.Customer;  
  12.   
  13.   
  14.   
  15. public class LogInterceptor extends EmptyInterceptor {  
  16.   
  17.     private int updates;  
  18.     private int creates;  
  19.   
  20.     private int loads;  
  21.   
  22.     public void onDelete(Object entity, Serializable id, Object[] state,  
  23.             String[] propertyNames, Type[] types) {  
  24.   
  25.         Date d = new Date(System.currentTimeMillis());  
  26.         String content = d.toGMTString() + ": delete  name: "  
  27.                 + entity.getClass().getName() + "  id: " + id;  
  28.         FileLog fl = new FileLog(content);  
  29.     }  
  30.   
  31.     public boolean onFlushDirty(Object entity, Serializable id,  
  32.             Object[] currentState, Object[] previousState,  
  33.             String[] propertyNames, Type[] types) {  
  34. System.err.println("!!!  some dirty !!!");  
  35.         updates++;  
  36.         Date d = new Date(System.currentTimeMillis());  
  37.         String content = d.toGMTString() + " : update name: "  
  38.                 + entity.getClass().getName() + "  id: " + id;  
  39.         FileLog fl = new FileLog(content);  
  40.         for (int i = 0; i < propertyNames.length; i++) {  
  41.             System.out.println(propertyNames[i] + ": " + previousState[i]  
  42.                     + "; " + currentState[i]);  
  43.         }  
  44.         System.out.println("??true??n or false   ");  
  45.   
  46.         return false;  
  47.     }  
  48.   
  49.     public boolean onLoad(Object entity, Serializable id, Object[] state,  
  50.             String[] propertyNames, Type[] types) {  
  51.   
  52.         loads++;  
  53.   
  54.         return true;  
  55.     }  
  56.   
  57.     public boolean onSave(Object entity, Serializable id, Object[] state,  
  58.             String[] propertyNames, Type[] types) {  
  59.         System.out.println("onsave2");  
  60.         creates++;  
  61.         Date d = new Date(System.currentTimeMillis());  
  62.         String content = d.toGMTString() + ": save  name: "  
  63.                 + entity.getClass().getName() + "  id: " + id;  
  64.         FileLog fl = new FileLog(content);  
  65.         /*if (entity instanceof BasicCar) { 
  66.             for (int i = 0; i < propertyNames.length; i++) { 
  67.  
  68.                 if ("date".equals(propertyNames[i])&&state[i]!=null) { 
  69.                     System.out.println(propertyNames[i] + ":statenull " + state[i]); 
  70.                     state[i] = new Date(System.currentTimeMillis()); 
  71.                     return true; 
  72.                 } 
  73.             } 
  74.         }*/  
  75.         if (entity instanceof Customer) {  
  76.             for (int i = 0; i < propertyNames.length; i++) {  
  77.   
  78.                 if ("salesname".equals(propertyNames[i])) {  
  79.                     System.out.println(propertyNames[i] + ":salesname!!@@ " + state[i]);  
  80.                     state[i] = "PPPPPP";  
  81.                     return true;  
  82.                 }  
  83.             }  
  84.         }  
  85.         System.out.println();  
  86.   
  87.         return false;  
  88.     }  
  89.   
  90.     public void afterTransactionCompletion(Transaction tx) {  
  91.         if (tx.wasCommitted()) {  
  92.             String content = "creations:" + creates + ",Updates:" + updates  
  93.                     + ",Loads:" + loads;  
  94.             System.out.println("creations:" + creates + ",Updates:" + updates  
  95.                     + ",Loads:" + loads);  
  96.             FileLog fl = new FileLog(content);  
  97.         }  
  98.         updates = 0;  
  99.         creates = 0;  
  100.         loads = 0;  
  101.     }  
  102.     public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException   
  103.     {  
  104.         System.out.println("collection!!!!!!!!"+collection.getClass().getName());  
  105.     }  
  106.     public String onPrepareStatement(String arg0) {  
  107.         String sqlString=arg0;  
  108.           
  109.     //    System.out.println("log       "+sqlString);  
  110.           
  111.             return sqlString;  
  112.     }  
  113.     public String getEntityName(Object arg0) throws CallbackException {  
  114.           
  115.         return null;  
  116.     }  
  117. }  


MyInterceptor.java:

[java]  view plain copy
  1. package interceptor;  
  2.   
  3. import java.io.Serializable;  
  4. import java.sql.Date;  
  5.   
  6. import org.hibernate.CallbackException;  
  7. import org.hibernate.EmptyInterceptor;  
  8. import org.hibernate.type.Type;  
  9.   
  10. import basicCar.bean.Account;  
  11.   
  12.   
  13.   
  14. public class MyInterceptor extends EmptyInterceptor {  
  15.   
  16.     public boolean onSave(Object entity, Serializable id, Object[] state,  
  17.                 String[] propertyNames, Type[] types) {  
  18.         System.out.println("onsave");  
  19.             if (entity instanceof Account) {  
  20.                 for (int i = 0; i < propertyNames.length; i++) {  
  21.                     if ("date".equals(propertyNames[i])&&state[i]!=null) {  
  22.                         System.out.println(propertyNames[i] + ":::" + state[i]);  
  23.                         state[i] = new Date(System.currentTimeMillis());  
  24.                         System.out.println(propertyNames[i] + ":##::" + state[i]);  
  25.                         return true;  
  26.                     }  
  27.                 }  
  28.             }  
  29.             return false;  
  30.         }  
  31.     public String onPrepareStatement(String arg0) {  
  32.         String sqlString=arg0;  
  33.           
  34.          // System.out.println("my       "+sqlString);  
  35.           
  36.             return sqlString;  
  37.     }  
  38. public String getEntityName(Object arg0) throws CallbackException {  
  39.           
  40.         return null;  
  41.     }  
  42.     }  




ChainedInterceptor.java:

[java]  view plain copy
  1. package interceptor;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Iterator;  
  5.   
  6. import org.hibernate.CallbackException;  
  7. import org.hibernate.EntityMode;  
  8. import org.hibernate.Interceptor;  
  9. import org.hibernate.Transaction;  
  10. import org.hibernate.type.Type;  
  11.   
  12. /** 
  13.  * Implementation of the Hibernate <code>Interceptor</code> interface that 
  14.  * allows the chaining of several different instances of the same interface. 
  15.  *  
  16.  * @author Laurent RIEU 
  17.  * @see Interceptor 
  18.  */  
  19. public class ChainedInterceptor implements Interceptor {  
  20.     // Interceptors to be chained  
  21.     private Interceptor[] interceptors;  
  22.   
  23.     public ChainedInterceptor() {  
  24.         super();  
  25.     }  
  26.   
  27.     public ChainedInterceptor(Interceptor[] interceptors) {  
  28.         super();  
  29.         this.interceptors = interceptors;  
  30.     }  
  31.   
  32.     public boolean onLoad(Object entity, Serializable id, Object[] state,  
  33.             String[] propertyNames, Type[] types) throws CallbackException {  
  34.         boolean result = false;  
  35.         for (int i = 0; i < interceptors.length; i++) {  
  36.             if (interceptors[i].onLoad(entity, id, state, propertyNames, types)) {  
  37.                 result = true;  
  38.             }  
  39.         }  
  40.         return result;  
  41.     }  
  42.   
  43.     public boolean onFlushDirty(Object entity, Serializable id,  
  44.             Object[] currentState, Object[] previousState,  
  45.             String[] propertyNames, Type[] types) throws CallbackException {  
  46.         boolean result = false;  
  47.         for (int i = 0; i < interceptors.length; i++) {  
  48.   
  49.             if (interceptors[i].onFlushDirty(entity, id, currentState,  
  50.                     previousState, propertyNames, types)) {  
  51.   
  52.                 result = true;  
  53.             }  
  54.         }  
  55.         return result;  
  56.     }  
  57.   
  58.     public boolean onSave(Object entity, Serializable id, Object[] state,  
  59.             String[] propertyNames, Type[] types) throws CallbackException {  
  60.         System.out.println("onsave3");  
  61.         boolean result = false;  
  62.         for (int i = 0; i < interceptors.length; i++) {  
  63.             if (interceptors[i].onSave(entity, id, state, propertyNames, types)) {  
  64.                 result = true;  
  65.             }  
  66.         }  
  67.         return result;  
  68.     }  
  69.   
  70.     public void onDelete(Object entity, Serializable id, Object[] state,  
  71.             String[] propertyNames, Type[] types) throws CallbackException {  
  72.         for (int i = 0; i < interceptors.length; i++) {  
  73.             interceptors[i].onDelete(entity, id, state, propertyNames, types);  
  74.         }  
  75.     }  
  76.   
  77.     public void preFlush(Iterator entities) throws CallbackException {  
  78.         for (int i = 0; i < interceptors.length; i++) {  
  79.             interceptors[i].preFlush(entities);  
  80.         }  
  81.     }  
  82.   
  83.     public void postFlush(Iterator entities) throws CallbackException {  
  84.         for (int i = 0; i < interceptors.length; i++) {  
  85.             interceptors[i].postFlush(entities);  
  86.         }  
  87.     }  
  88.   
  89.     public Boolean isTransient(Object entity) {  
  90.         Boolean result = false;  
  91.         for (int i = 0; i < interceptors.length; i++) {  
  92.             result = interceptors[i].isTransient(entity);  
  93.             if (result != null) {  
  94.                 result=true;  
  95.             }  
  96.         }  
  97.         return result;  
  98.     }  
  99.   
  100.   
  101.     static int l = 0;  
  102.   
  103.     public int[] findDirty(Object entity, Serializable id,  
  104.             Object[] currentState, Object[] previousState,  
  105.             String[] propertyNames, Type[] types) {  
  106.           
  107.         //这里必须初始化为空,否则其内里interceptor的任何改变都会被改回去  
  108.         int[] result = {};  
  109.           
  110.         boolean someDirty = onFlushDirty(entity, id, currentState,  
  111.                 previousState, propertyNames, types);  
  112.         if (someDirty == false)  
  113.             return result;  
  114.   
  115.         if (l < interceptors.length) {  
  116.             result = interceptors[l].findDirty(entity, id, currentState,  
  117.                     previousState, propertyNames, types);  
  118.             l++;  
  119.             return result;  
  120.         }  
  121.         l = 0;  
  122.   
  123.         return result;  
  124.     }  
  125.   
  126.     static int m = 0;  
  127.   
  128.     public Object instantiate(String entityName, EntityMode entityMode,  
  129.             Serializable id) throws CallbackException {  
  130.         Object result = null;  
  131.         if (m < interceptors.length) {  
  132.             result = interceptors[m].instantiate(entityName, entityMode, id);  
  133.             m++;  
  134.             return result;  
  135.         }  
  136.         m = 0;  
  137.         return result;  
  138.     }  
  139.   
  140.     public Interceptor[] getInterceptors() {  
  141.         return interceptors;  
  142.     }  
  143.   
  144.     public void setInterceptors(Interceptor[] interceptors) {  
  145.         this.interceptors = interceptors;  
  146.     }  
  147.   
  148.     public void afterTransactionBegin(Transaction arg0) {  
  149.         for (int i = 0; i < interceptors.length; i++) {  
  150.             interceptors[i].afterTransactionBegin(arg0);  
  151.         }  
  152.     }  
  153.   
  154.     public void afterTransactionCompletion(Transaction arg0) {  
  155.         for (int i = 0; i < interceptors.length; i++) {  
  156.             interceptors[i].afterTransactionCompletion(arg0);  
  157.         }  
  158.   
  159.     }  
  160.   
  161.     public void beforeTransactionCompletion(Transaction arg0) {  
  162.         for (int i = 0; i < interceptors.length; i++) {  
  163.             interceptors[i].beforeTransactionCompletion(arg0);  
  164.         }  
  165.     }  
  166.   
  167.     static int n = 0;  
  168.   
  169.     public Object getEntity(String arg0, Serializable arg1)  
  170.             throws CallbackException {  
  171.         Object entity = null;  
  172.         if (n < interceptors.length) {  
  173.             entity = interceptors[n].getEntity(arg0, arg1);  
  174.             n++;  
  175.             return entity;  
  176.         }  
  177.         n = 0;  
  178.         return entity;  
  179.     }  
  180.   
  181.     static int i = 0;  
  182.   
  183.     public String getEntityName(Object arg0) throws CallbackException {  
  184.         String entityName = null;  
  185.         if(i < interceptors.length) {  
  186.             entityName = interceptors[i].getEntityName(arg0);  
  187.             i++;      
  188.             return entityName;        
  189.         }  
  190.         i=0;  
  191.         return entityName;  
  192.     }  
  193.   
  194.     public void onCollectionRecreate(Object arg0, Serializable arg1)  
  195.             throws CallbackException {  
  196.         for (int i = 0; i < interceptors.length; i++) {  
  197.             interceptors[i].onCollectionRecreate(arg0, arg1);  
  198.         }  
  199.     }  
  200.   
  201.     public void onCollectionRemove(Object arg0, Serializable arg1)  
  202.             throws CallbackException {  
  203.         for (int i = 0; i < interceptors.length; i++) {  
  204.             interceptors[i].onCollectionRemove(arg0, arg1);  
  205.         }  
  206.     }  
  207.   
  208.     public void onCollectionUpdate(Object arg0, Serializable arg1)  
  209.             throws CallbackException {  
  210.         for (int i = 0; i < interceptors.length; i++) {  
  211.             interceptors[i].onCollectionUpdate(arg0, arg1);  
  212.         }  
  213.   
  214.     }  
  215.   
  216.     static int k = 0;  
  217.   
  218.     public String onPrepareStatement(String arg0) {  
  219.         String sqlString = arg0;  
  220.         if (k < interceptors.length) {  
  221.             sqlString = interceptors[k].onPrepareStatement(sqlString);  
  222.             k++;  
  223.             return sqlString;  
  224.         }  
  225.         System.out.println("kkk  != null " + k + "  " + sqlString);  
  226.         k = 0;  
  227.         return sqlString;  
  228.     }  
  229. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值