利用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" name="code"><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]