hibernate 查询计数

标签 hibernate

有没有办法计算 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/

相关文章:

java - 2 个持久单元之间的 Hibernate 链接?

java - 如何配置 hibernate 配置文件以拥有来自同一数据库的多个实例?

hibernate - JPA/Hibernate 同一实体的多种表示

java - 我可以从数据库中的 blob 加载 Spring contextConfigLocation 吗?

hibernate 查询自动刷新

java - 在 hibernate 查询中返回通用对象而不是类实体

C#读取Spring框架连接字符串

hibernate - 如何升级 Hibernate 4.3 --> 5.2?

java - 更新 hibernate 关联

java - 将 hibernate 查询结果转换为类类型的对象而不是列表数组