Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we test for the N+1 problem in JPA/Hibernate?

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

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;
}

And a very simple service:

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;

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

like image 787
Rémi Birot-Delrue Avatar asked Apr 26 '19 17:04

Rémi Birot-Delrue


2 Answers

As option you can verify count of queries (fetch, updates, inserts) in the test

 repository.findById(10L);

 SessionFactory sf = em.getEntityManagerFactory().unwrap(SessionFactory.class);
 Statistics statistics = sf.getStatistics();

 assertEquals(2L, statistics.getQueryExecutionCount());

See hibernate statistic

like image 129
kolomiets Avatar answered Sep 19 '22 09:09

kolomiets


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

like image 40
Lesiak Avatar answered Sep 21 '22 09:09

Lesiak