title: Detach JPA objects with lazy initialized properties
body: <p>There are two JPA entities: User and Order with one-to-many relationship.</p>
  
  <pre><code>/**
   * User DTO
   */
  @Entity
  @Table(name="user")
  public class User implements Serializable {
      private static final long serialVersionUID = 8372128484215085291L;
  
      private Long id;
      private Set&lt;Order&gt; orders;
  
      public User() {}
  
      @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sequenceUser")
      public Long getId() {
          return this.id;
      }
      private void setId(Long id) {
          this.id = id;
      }
  
      @OneToMany(mappedBy="user", cascade=CascadeType.PERSIST, fetch=FetchType.LAZY)
      @LazyCollection(LazyCollectionOption.EXTRA)
      public Set&lt;Order&gt; getOrders() {
          return orders;
      }
      public void setOrders(Set&lt;Order&gt; orders) {
          this.orders = orders;
      }
   }
  
  
  /**
   * Order DTO
   */
  @Entity
  @Table(name="order")
  public class Order implements Serializable {
      private static final long serialVersionUID = 84504362507297200L;
  
      private Long id;
      private User user;
  
      public Order() {
      }
  
      @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sequenceOrder")
      public Long getId() {
          return this.id;
      }
      private void setId(Long id) {
          this.id = id;
      }
  
      @ManyToOne
      @JoinColumn(name="user_id")
      public User getUser(){
          return user;
      }
      public void setUser(User user){
          this.user = user;
      }
  }
  </code></pre>
  
  <p>I use these entities in my service layer classes where every method runs in transaction. Everything is fine except cases when methods of service layer classes must return these entities.</p>
  
  <pre><code>@Transactional(readOnly=true)
  public Set&lt;Order&gt; getOrders() {
      Set&lt;Order&gt; orders = user.getOrders();
  
      return orders;
  }
  </code></pre>
  
  <p>This method returns data well. But when I try access to received collection elements I catch exception: "org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: package.User.orders, no session or session was closed".</p>
  
  <p>So, it was excepted. I thought that detaching result will solve my problem, but trick like this</p>
  
  <pre><code>@Transactional(readOnly=true)
  public Set&lt;Order&gt; getOrders() {
      Set&lt;Order&gt; orders = user.getOrders();
  
      for(Order order: orders)
          entityManager.detach(order);
      return orders;
  }
  </code></pre>
  
  <p>didn't change anything :(</p>
  
  <p>It doesn't matter for me will info about users attend in set of orders or not. I just want to work with this set and not going to modify it.</p>
  
  <p>Can anybody help me? :)</p>