验证 spring jpa 存储库执行的查询

问题描述 投票:0回答:1

我们有一个 spring 存储库,由于行为的改变,我们的延迟加载停止工作。我们注意到正在执行多个查询来加载相关对象。

我们已经解决了这个问题,但我想编写一个测试来告诉我们正在运行哪些查询,或者至少检查我们没有查询特定的表。

我环顾四周,找不到任何例子。我认为

TestEntityManager
可能会有所帮助,但该类没有验证方法。

有人得到任何指示,或编写了验证类似行为的测试吗?

java hibernate spring-data-jpa
1个回答
0
投票

我使用休眠统计找到了一个非常优雅的解决方案:

//Enable hibernate statistics
@DataJpaTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
public class MyRepositoryIT {

    @Autowired
    private MyRepository repository;

    @Autowired
    private EntityManager entityManager;

    @Test
    @Transactional
    @Sql
    void shouldNotQueryLazilyRelatedEntities() {
        //Query repository and check result is not null
        MyEntity response = repository.findById(1L);
        assertThat(response).isNotNull();

        //Load statistics from entity manager session
        Session session = entityManager.unwrap(Session.class);
        Statistics statistics = session.getSessionFactory().getStatistics();

        //Assert that only the expected entity is loaded, and not the lazy relationships.
        assertThat(statistics.getEntityLoadCount()).isEqualTo(1);
        assertThat(statistics.getEntityStatistics(MyEntity.class.getName()).getLoadCount()).isEqualTo(1);
        assertThat(statistics.getEntityStatistics(LazyRelation.class.getName()).getLoadCount()).isEqualTo(0);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.