title: how to lazy load collection when using spring-data-jpa, with hibernate, from an console application
body: <p>I have an small console application and I am using spring-data-jpa with hibernate. I really can not figure out how to lazy initialize collections when using spring-data-jpa with its repositories, in an standalone console application. Here is some of my code:</p>
  
  <pre><code>@Entity
  public class User {
  ...
      @OneToMany(cascade=CascadeType.ALL)
      @JoinColumn(name="USER_ORDER_ID")
      private Set&lt;Order&gt; orders = new HashSet&lt;Order&gt;();
  ...
  }
  </code></pre>
  
  <p>repository:</p>
  
  <pre><code>public interface UserRepository extends PagingAndSortingRepository&lt;User, Long&gt; {
  
      public ArrayList&lt;User&gt; findByFirstNameIgnoreCase(String firstName);
  }
  </code></pre>
  
  <p>service impl:</p>
  
  <pre><code>@Service
  @Repository
  @Transactional
  public class UserServiceImpl implements UserService {
      @Autowired
      private UserRepository userRepository;
  
  public ArrayList&lt;User&gt; findByFirstNameIgnoreCase(String firstName) {
      ArrayList&lt;User&gt; users = new ArrayList&lt;User&gt;();
      users = userRepository.findByFirstNameIgnoreCase(firstName);
      return users;
  }
  </code></pre>
  
  <p>my main method:</p>
  
  <pre><code>...
  user = userRepository.findByFirstNameIgnoreCase("john").get(0);
  orders = user.getOrders();
  for (Order order : orders) {
    LOGGER.info("getting orders: " + order.getId());
  }    
  </code></pre>
  
  <p>the foreach loop gets an exception:</p>
  
  <p>EVERE: failed to lazily initialize a collection of role: com.aki.util.User.orders, no session or session was closed
  org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:</p>
  
  <p><strong>Please note that I do not have this problem when running this from an webapp with some kind of OpenSessionInViewFilter.</strong></p>