標籤:style blog http color os io java ar div
Hibernate的攔截器,有很大作用。比如要監控SQL的執行效率等。
參考文檔:
http://docs.jboss.org/hibernate/orm/3.5/reference/zh-CN/html/events.html
下面是一個簡單的監控Hibernate的操作SQL列印:
建立一個Java類:
package com.my.dao.util;import org.hibernate.EmptyInterceptor;@SuppressWarnings("serial")public class AuditInterceptor extends EmptyInterceptor { @Override public String onPrepareStatement(String sql) { System.out.println(sql); return super.onPrepareStatement(sql); } }
在Hibernate的Configuration中加入這句:
configuration.setInterceptor(new AuditInterceptor());
完整HibernateUtil
package com.my.dao.util;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.setInterceptor(new AuditInterceptor()); return configuration.configure().buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
[Hibernate] - Interceptors and events