RNJ*_*RNJ 7 java sql hibernate
我对hibernate有一些性能问题,因为它会多次访问数据库.我正在研究一些获取策略.我想写一些功能单元测试,以便我的应用程序发展,我可以看到有多少SQL语句被调用.
我想知道我是否可以计算调用多少个SQL语句.目前我将show-sql设置为true,然后计算控制台中的SQL.如果可能的话,我想在代码中执行此操作.是否可以计算hibernate在代码中使用多少个SQL?
谢谢
编辑
在@AleksanderBlomskøld回复之后....
我的测试用例是
StatisticsService statisticsService = new StatisticsService();
Session session = entityManager.unwrap(Session.class);
statisticsService.setSessionFactory(session.getSessionFactory());
statisticsService.setStatisticsEnabled(true);
List<MyType> r= entityManager.createQuery("from MyType", MyType.class).getResultList();
System.out.println(statisticsService.getQueryExecutionCount());
System.out.println(statisticsService.getQueries()[0]);
Run Code Online (Sandbox Code Playgroud)
查询执行计数为1,如果我查看查询,则表明它是"来自MyType"
但是在日志中的sql语句中,我可以看到有SQL语句来检索MyType及其许多相关类.所以事实上我想知道因为"来自MyType"调用而攻击数据库的所有SQL.
我需要更清楚的是什么?或者我只是滥用StatisticService
谢谢
在Hibernate中启用统计信息并使用统计服务.配置会话工厂时,请确保设置hibernate.generate_statistics = true.然后,您可以通过JMX或以编程方式访问统计信息:
//Enable statistics
StatisticsService statisticsService = new StatisticsService();
statisticsService.setSessionFactory(sessionFactory);
statisticsService.setStatisticsEnabled(true);
// Do queries...
//...
///Print out stats:
System.out.println(statisticsService.getQueryExecutionCount());
Run Code Online (Sandbox Code Playgroud)