title: Hibernate + Spring Data - proxy or real object?
body: <p>Ok, maybe a noob question but I'm a bit confused about when Hibernate returns the real object and when its proxy, example - I use JpaRepository and its <code>save()</code> method seems to return the object itself, meaning that all the lazy collections are null. <br>So, is there a) some rule to determine whether the method of repository would return entity or proxy, and b) should I always check collections for null in the code?</p>
  
  <p>UPD: did some debugging, in current transaction even <code>repository.getOne(id)</code> returns the object itself, meanwhile when I enter id of the object which had been stored in DB earlier I get the proxy, as I would expect. now I'm even more puzzled :) <br/> <code>saveAndFlush()</code> changes nothing</p>
  
  <p>UPD2: code example, hope that helps</p>
  
  <pre><code>@Entity
  public class MyEntity {
  
  @Id
  @GeneratedValue
  private Integer id;
  
  @Column(nullable = false, unique = true, insertable=false)
  private String dbGeneratedField;
  
  @OneToMany(mappedBy = "myEntity", fetch = FetchType.LAZY)
  private List&lt;OtherEntity&gt; otherEntities;
  
  //getters, setters and stuff
  
  }
  
  // service method
  @Transactional
  public createMyEntity() {  
  MyEntity entity = new MyEntity();
  // set some necessary fields but not id
  
  MyEntity e1 = myEntityRepository.save(entity);
  return e1;
  }
  
  // repository
  public interface MyEntityRepository extends JpaRepository&lt;MyEntity, Integer&gt; {}
  </code></pre>
  
  <p>so, my expectation that <code>e1</code> should be either proxy or fully initialized object (meaning that collections are not null), instead of it I get the reference to <code>entity</code> object. When after save was called (suppose it received id=111) I call <code>repository.findOne(111)</code> I again get the same reference, though, when I enter this method next time (other transaction, saving another entity) and perform <code>repository.findOne(111)</code> it returns the proxy as I'd expect it from beginning.</p>