我们如何在JPA/Hibernate中测试N + 1问题? [英] How can we test for the N+1 problem in JPA/Hibernate?

查看:79
本文介绍了我们如何在JPA/Hibernate中测试N + 1问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了N + 1问题,我想编写某种自动回归测试,因为它会极大地影响性能.

I have a N+1 problem, and I’d like to write some kind of automated regression test because it impacts performance very much.

我考虑过间谍EntityManager并验证其方法createQuery()仅被调用一次,但是Hibernate不会使用它来初始化惰性关系,因此它不起作用.我也可以尝试关闭存储库和服务之间的JPA事务(或分离我的实体),并查找异常,但这确实是一个丑陋的主意.

I thought about spying the EntityManager and verifying its method createQuery() is called only once, but Hibernate don’t use it to initialize lazy relationships, thus it didn’t work. I could also try to shut down the JPA transaction between my repository and my service (or detach my entity) and look out for exceptions, but it’s really an ugly idea.

要给我们一个框架,假设我们有一个非常简单的父子模型:

To give us a frame, let’s say we have a very simple parent-child model:

@Entity
public class Parent {
    …
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    private Collection<Child> children;
}

@Entity
public class Child {
    …
    @ManyToOne
    private Parent parent;
}

一个非常简单的服务:

public class MyService {
    …
    public void doSomething(Long parentId) {
        Parent parent = …; /* retrieve Parent from the database */
        doSomeOtherThing(parent.getChildren());
    }
}

从数据库中检索父项可以使用以下两个查询:

Parent retrieval from database could use the two following queries:

SELECT parent FROM Parent parent WHERE parent.id = :id;
SELECT parent FROM Parent parent JOIN FETCH parent.children WHERE parent.id = :id;

当我用第一个查询而不是第二个查询检索我的Parent实体时,我该如何编写一个崩溃的测试?

How may I write a test that crashes when I retrieve my Parent entity with the first query, but not the second?

推荐答案

请参阅以下解决方案,该解决方案依赖于包装DataSource https://vladmihalcea.com/如何在测试期间检测n个以上的查询问题/

Refer to following solution, which relies on wrapping your DataSource https://vladmihalcea.com/how-to-detect-the-n-plus-one-query-problem-during-testing/

这篇关于我们如何在JPA/Hibernate中测试N + 1问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆