利用Spring AOP记录Hibernate统计信息

在Hibernate的属性里设置hibernate.generate_statistics为true.

<prop key="hibernate.generate_statistics">true</prop>
 

编写切面类PerformanceInfo.java

org.hibernate.stat.Statistics包含统计信息,如二级缓存等.根据需要记录相应内容.

 

package ssh.core;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class PerformanceInfo {
	
	Logger log = Logger.getLogger(this.getClass());
	
	public void printInfo(){
		SessionFactory sf = (SessionFactory) getBean("sessionFactory");
		printHibernateStatistics(sf.getStatistics());
	}
	
	private void printHibernateStatistics(Statistics statistics){
		log.debug(statistics);
	}
	
	public static Object getBean(String beanName){
		ServletContext servletContext = ServletActionContext.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		return ctx.getBean(beanName);
	}
}
 

 

配置Spring AOP

 

修改applicationContext.xml

加入切面类

<bean id="performanceInfo" class="ssh.core.PerformanceInfo"/>

 AOP,根据需要修改execution以及切面类的method

	<aop:config>
		<aop:aspect id="performance" ref="performanceInfo">
			<aop:pointcut id="allDAO" expression="execution(* ssh.dao.*.*.*(..))"/>
			<aop:after method="printInfo" pointcut-ref="allDAO"/>
		</aop:aspect>
	</aop:config>

 

日志记录Log4j配置详见 http://gary0416.iteye.com/blog/857139

 

部分运行结果

2011-03-19 07:50:50 DEBUG [ssh.core.PerformanceInfo.printHibernateStatistics(PerformanceInfo.java:35)] - Statistics[start time=1300492114615,sessions opened=7,sessions closed=6,transactions=10,successful transactions=5,optimistic lock failures=0,flushes=1,connections obtained=6,statements prepared=7,statements closed=7,second level cache puts=21,second level cache hits=2,second level cache misses=0,entities loaded=21,entities updated=1,entities inserted=0,entities deleted=0,entities fetched=0,collections loaded=0,collections updated=0,collections removed=0,collections recreated=0,collections fetched=0,queries executed to database=6,query cache puts=0,query cache hits=0,query cache misses=0,max query time=297]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值