title: JPA 2.0 / Hibernate: Why does LAZY fetching with "@OneToOne" work out of the box?
body: <p>my question is regarding JPA 2.0 with Hibernate, @OneToOne relationships and lazy loading.</p>
  
  <p>First my setup:</p>
  
  <ul>
  <li>Spring 3.0.5.RELEASE</li>
  <li>SprnigData JPA 1.0.1.RELEASE</li>
  <li>Hibernate 3.5.2-Final</li>
  <li>DBMS: PostgreSQL 9.0</li>
  </ul>
  
  <p>I recently came across the fact, that a @OneToOne relationship can't be fetched the lazy way (FetchType.LAZY), at least not without byte code instrumentation, compile time weaving or the like. Many sites out there say this, for example:</p>
  
  <ul>
  <li><a href="http://community.jboss.org/wiki/SomeExplanationsOnLazyLoadingone-to-one" rel="nofollow noreferrer">http://community.jboss.org/wiki/SomeExplanationsOnLazyLoadingone-to-one</a></li>
  <li><a href="http://justonjava.blogspot.com/2010/09/lazy-one-to-one-and-one-to-many.html" rel="nofollow noreferrer">http://justonjava.blogspot.com/2010/09/lazy-one-to-one-and-one-to-many.html</a></li>
  <li><a href="https://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy">Making a OneToOne-relation lazy</a></li>
  </ul>
  
  <p>The thing is, with my setup, a lazy loading of a @OneToOne entity seems to work "out of the box", and I really would like to understand why. Please, have a look at my unit test:</p>
  
  <pre><code>@Test
  @Transactional
  public void testAvatarImageLazyFetching()
  {
      User user = new User();
      user.setAvatarImage( new AvatarImage() );
  
      User = userRepository.save( user );
  
      entityManager.flush();
      entityManager.clear();
  
      User loadedUser = userRepository.findOne( user.getId() );
      assertNotNull( loadedUser );
  
      PersistenceUtil persistenceUtil = Persistence.getPersistenceUtil();
  
      assertTrue( persistenceUtil.isLoaded( loadedUser ) );
      assertFalse( persistenceUtil.isLoaded( loadedUser, "avatarImage" ) );
  }
  </code></pre>
  
  <p>This test case is successful, and in Hibernates SQL logging output, I can see clearly, that the "avatarImage" will not be fetched, just the "user" (just a single SELECT, no JOIN, no access to the "AvatarImage" table etc.)</p>
  
  <p>The unidirectional @OneToOne relationshop in the User class looks like this:</p>
  
  <pre><code>@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.LAZY )
  private AvatarImage    avatarImage;
  </code></pre>
  
  <p>So, everything very simple - and it seems to work.</p>
  
  <p>To repeat my question: why is it working, why can the "AvatarImage" be fetched lazily, although it is referenced with a @OneToOne association?</p>
  
  <p>I really appreciate any help you can offer</p>
  
  <p>Thanks a lot!</p>