有没有办法计算 Hibernate 在事务或线程中内部完成的查询数量?我研究了 Hibernate 拦截器,但不清楚我应该覆盖哪些 API 来增加计数器。我的目标是构建一个警报,在某个请求的查询计数超过某个阈值时通知我,以便我可以根据需要对其进行优化。
谢谢,
山姆
最佳答案
这个问题很老,但我认为它可以帮助其他人。
库 Spring Hibernate Query Utils ( https://github.com/yannbriancon/spring-hibernate-query-utils ) 为每个线程提供一个查询计数器,可用于集成测试以检查每个请求生成的查询数量。
README 中有一个例子:
...
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);
}
}
关于 hibernate 查询计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9985404/