首页 > 系统服务 > 详细

[Hibernate] - Interceptors and events

时间:2014-09-03 19:46:17      阅读:293      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/HD/p/3954323.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!