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?
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
Refer to following solution, which relies on wrapping your DataSource
https://vladmihalcea.com/how-to-detect-the-n-plus-one-query-problem-during-testing/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With