有没有办法在事务或线程中统计Hibernate内部执行的查询次数?我研究了Hibernate拦截器,但不清楚应该覆盖哪些API来增加计数器。我的目标是构建一个警报,当某个请求的查询次数超过某个阈值时通知我,以便我可以根据需要进行优化。
谢谢,
Sam
谢谢,
Sam
...
import com.yannbriancon.interceptor.HibernateQueryInterceptor;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class NotificationResourceIntTest {
@Autowired
private HibernateQueryInterceptor hibernateQueryInterceptor;
@Test
public void saveFile_isOk() throws Exception {
// Initialize the query to 0 and allow the counting
hibernateQueryInterceptor.startQueryCount();
// Call the resource that we want to test
MvcResult result = mvc.perform(get("/rest/notifications"))
.andExpect(status().isOk())
.andReturn();
// Get the query count for this thread and check that it is equal to the number of query you expect, let's say 4.
// The count is checked and we detect potential n+1 queries.
Assertions.assertThat(hibernateQueryInterceptor.getQueryCount()).isEqualTo(4);
}
}
SessionFactory sessionFactory = getSessionFactoryForApplication();
Statistics stats = sessionFactory.getStatistics();
stats.setStatisticsEnabled(true);
// All of the queries that have executed.
String[] queries = stats.getQueries();
And so on...
@Test
@AssertHibernateSQLCount(inserts = 1)
void create_one_entity_from_endpoint() {
BlogPost requestBody = new BlogPost("My new blog post");
BlogPost responseBody = restTemplate.postForObject("/blogPosts", requestBody, BlogPost.class);
assertEquals("My new blog post", responseBody.getTitle(), "The blog post created is returned");
}