title: Spring Boot Data JPA: Hibernate Session issue
body: <p>I'm developing a Spring Boot based web application. I heavily rely on <code>@ComponentScan</code> and <code>@EnableAutoConfiguration</code> and <strong>no explicit XML</strong> configuration in place.</p>
  
  <p>I have the following problem. I have a <strong>JPA</strong>-Annotated Entity class called <code>UserSettings</code>:</p>
  
  <pre><code>@Entity public class UserSettings {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
  
      @OneToMany(cascade = CascadeType.ALL)
      private Set&lt;Preference&gt; preferences; // 'Preference' is another @Entity class
  
      public UserSettings() {
           this.preferences = new HashSet&lt;Preference&gt;();
      }
  
  // some more primitive properties, Getters, Setters...
  }
  </code></pre>
  
  <p>I followed <a href="https://spring.io/guides/gs/accessing-data-jpa/" rel="nofollow noreferrer">this</a> tutorial and created a repository interface that extends <code>JpaRepository&lt;UserSettings,Long&gt;</code>. </p>
  
  <p>Furthermore, I have a <code>UserManager</code> bean:</p>
  
  <pre><code>@Component public class SettingsManager {
  
  @Autowired
  UserSettingsRepository settingsRepository;
  
  @PostConstruct
  protected void init() {
      // 'findGlobalSettings' is a simple custom HQL query 
      UserSettings globalSettings = this.settingsRepository.findGlobalSettings();
      if (globalSettings == null) {
          globalSettings = new UserSettings();
          this.settingsRepository.saveAndFlush(globalSettings);
      }
  }
  </code></pre>
  
  <p>Later in the code, I load the <code>UserSettings</code> object created here, again with the <code>findGlobalSetttings</code> query. </p>
  
  <p>The problem is: Every time I try to access the <code>@OneToMany</code> attribute of the settings object, I get the following exception:</p>
  
  <blockquote>
    <p>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role org.example.UserSettings.preferences, could not initialize proxy - no Session</p>
  </blockquote>
  
  <p>I understand that each HTTP Session has its own Hibernate Session, as described in the accepted answer of <a href="https://stackoverflow.com/questions/16752799/could-not-initialize-proxy-no-session">this question</a>, but that does not apply in my case (currently I'm testing this within the same HTTP Session), which is why I have no idea where this exception comes from.</p>
  
  <p>What am I doing wrong and how can I achieve circumvent the error?</p>