Search code examples
javahibernatespring-data-jpa

Verify the queries executed by spring jpa repository


We've got a spring repository, and due to a change of behaviour, our lazy loading stopped working. We noticed that multiple queries were being executed to load the related objects.

We've fixed the issue, but I'd like to write a test to tell us what queries we're running, or at least check we're not querying specific tables.

I've had a look around, and I can't find any examples. I thought the TestEntityManager might help, but there's no validation methods on that class.

Has anyone got any pointers, or written a test which validates similar behaviour?


Solution

  • I found a pretty elegant solution to this using hibernate statistics:

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