javahibernatejpaspringsource

How Can I create a Unit Test in Java that Can ensure that my JPA database entities are being loaded lazily?


I would like to create unit tests for the persistence tier of my project to ensure that entities are being loaded lazily. I am using hibernate with springsource. What is a basic unit test that can guarantee that I can create an Assertion to check that? The challenge here for me at least is that while in the transaction I cannot tell if the entities are being fetched lazily and loaded upon demand or eagerly fetched.

Thanks


Solution

  • If you have a detached object, when you try to access the property, hibernate will throw a LazyInitializationException.

    @Test(expected=LazyInitializationException.class)
    public void lazyLoadTest() {
      //get a session object
      Session session = dao.getSession(); 
    
      //load object
      Foo foo = dao.findById(1);
    
      //if you have a detached object, this would be unnessary
      session.close();  
    
      //if lazy loading is working, an exception will be thrown
      //note: If you don't try to access the collection (.size(), the data will not be fetched)
      foo.getBars().size(); 
    }
    

    You can also use Hibernate.isInitialized

    @Test
    public void anotherLazyLoadTest() {
          //get a session object
          Session session = dao.getSession(); 
    
          //load object
          Foo foo = dao.findById(1);
    
          //if you have a detached object, this would be unnessary
          session.close();  
    
          boolean isInitialized = Hibernate.isInitialized(foo.getBars());
          assertFalse(isInitialized);
    }